John Davidson

php - Modify data extracted from rss file with simplexml

0 comments
Message:


I am extracting data from an rss file using simplexml. The urls in are wrong and I am trying to change them.
To be able to use the data, I need to strip everything before the word "base" in those urls.


I can do it with the following:


<?php echo strstr($rss->channel->item[0]->link, 'base') ?: $rss->channel->item[0]->link;?>
<?php echo strstr($rss->channel->item[1]->link, 'base') ?: $rss->channel->item[1]->link;?>
<?php echo strstr($rss->channel->item[2]->link, 'base') ?: $rss->channel->item[2]->link;?>
etc...

but its looks messy and I'm pretty sure there is a way to do it more efficiently without having to call the strstr function over and over again.


I tried many things and the following gave me the best result:


foreach($rss->channel->item->link as $b)
{
$new_url[] = strstr($b, 'base') ?: $b;
}

but when I call it with:


<?php echo $new_url[0];?>
<?php echo $new_url[1];?>
<?php echo $new_url[2];?>

it only works on the first instance.


Any idea? Or am I completely wrong about this?



My Answer:
"src=" in the url and replace it with a new url. Here's an example of how you can achieve this:

php
// Load the rss file
$xml = simplexml_load_file('rss.xml');

// Loop through each item in the rss file
foreach ($xml->channel->item as $item) {
// Get the url from the item
$url = (string) $item->link;

// Find the position of "src=" in the url
$pos = strpos($url, 'src=');

// If "src=" is found in the url
if ($pos !== false) {
// Strip everything before "src=" and replace it with a new url
$newUrl = 'https://newurl.com/' . substr($url, $pos + 4);

// Update the url in the item
$item->link = $newUrl;
}
}

// Save the modified rss file
$xml->asXML('modified_rss.xml');


In this code snippet, we are loading the rss file, looping through each item, extracting the url, finding the position of "src=" in the url, and then replacing everything before "src=" with a new url. Finally, we save the modified rss file with the updated urls.

Rate this post

5 of 5 based on 1191 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us