I’ve finally set up an RSS feed for this site and one of the things I needed to sort out was the use of URLs and image tags. All the anchor tags in this site are relative, and so are all the image sources. This isn’t going to work in an RSS feed because it would mean none of the links would work, and the images would all be broken. Fortunately this is easy to fix with the use of PHP’s string replacement functions.
Let’s say for example’s sake, that I have an associative array of data which has been fetched from the database with the following fields:
- content – the actual HTML content for the page content. This contains HTML tags in it ie it’s not just plain text. This is also the main content for the RSS feed, used in the <content:encoded> field.
- description – the short description used on search results pages and category pages in this site. This is used in the RSS feed for the short description as well, in the <description> field. It also contains HTML as per the content field.
- fullurl – the full url for the page, not including the domain name, but including leading and trailing slashes. For example, with this very post the value would be /replace-relative-urls-with-absolute-urls-php/
All image src attributes start with src="/images
and anchor hrefs href="/
or href="#
, so it’s really easy to convert these from relative URLs to full absolute URLs.
The code to do the replacement is as simple as this (I’ll explain it all in a little more detail below):
foreach(array('content', 'description') as $fieldname) { $article[$fieldname] = str_replace( array( 'src="/images/', 'href="/', 'href="#' ), array( 'src="https://electrictoolbox.com/images/', 'href="https://electrictoolbox.com/', "href="https://electrictoolbox.com{$article['fullurl']}#" ), $article[$fieldname] ); }
The foreach(array('content', 'description') as $fieldname)
foreach loop means there’s no copying and pasting of code to run the same replacement function twice, and also means if I ever need to add any more fields into the replacement then I can simply add it into the array and the replacements will be done on that too.
The rest of the code should be pretty clear. It’s possible to pass arrays into the PHP str_replace() function as I have done above, instead of calling it multiple times. The first element of the first array is replace with the first element of the second array, and so on.
Instead of hard coding the website address into it, I could have used the $_SERVER['HTTP_HOST']
address instead. That would make the code more portable.