Using the MODX API to parse content and update links to use full/absolute URLs

26 August 2020
Read time: 3 mins

Written by:
Graeme Leighfield.

Here's a handy bit of code that should help you out if you want to take some user entered content and ensure that all URL's in it are referencing the complete web address.

Day in day out, we create highly bespoke websites that enhance our clients digital lives, that are empowered by using the MODX CMS - our use case here was that we wanted our client to have a rich text editor, where they could write content into it which would ultimately end up in an email. Because of this, there was a chance that the URLs entered could be relative, not complete, resulting it links from the email being broken (as its missing the websites URL!)

This code is free to use, however please use at your own risk.

Make your snippet:

<?php
$tv = $modx->getObject('modTemplateVarResource', array(
    'tmplvarid' => 28, //ID of our TV that contains the content we want to check.
    'contentid' => $id, //ID of the resource
));

if ($tv) {
    $content = $tv->get('value');
    $dom = new DOMDocument();
    $dom->loadHTML(utf8_decode($content));
    $links = $dom->getElementsByTagName('a');
    foreach ($links as $link) {
        $url = $link->getAttribute('href');

        if (strpos($url, '[[~') || strpos($url, ']]')) {
            $url = $modx->makeUrl(str_replace(array('', ']]', '~'), '', $url), '', '', 'full');
        }

        $link->setAttribute('href', $url);
    }

    return $dom->saveHTML();
} else {
    //Error?
}

You may notice that we want to get the RAW/Unprocessed TV Value in the example below, thats because doing:

$content = $resource->getTVValue('tv_name');

returns the already processed content, i.e the URL would already be in there. In the example above, we're getting the TV Content direct from the modTemplateVarResource table, and then getting it's raw value by calling

$tv->get('value');

After that, we're using the built in makeUrl method to create a full, complete and accurate URL to the MODX resource in question. The fun part, that resource link can be a web page, a static resource... who knows - anything!

Ta-dah! (Jazz hands)

That's it! You're all done! Lots of possibilities with this one, and if anything, it's a great example about how to get, then process raw TV values.

Enjoy!

G

Need MODX consultancy or support?

Do you need help with your MODX CMS website? Then we are here to help. We're MODX professionals with over 10 years of professional experience spanning all possible uses of the CMS platform.


Written by:
Graeme Leighfield.

Share this article:

Read more from us on:

Related articles.

Send us a message.

hello@gelstudios.co.uk

01793 677150

Unit 8, Lancaster Place,
South Marston Park, Swindon, SN3 4UQ