Skip to content
Advertisement

Modify data extracted from rss file with simplexml

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?

Advertisement

Answer

Using foreach($rss->channel->item->link as $b) will give the link in $b

The items have a link property, so in that case you can loop the items.

The code could be

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

Note that using strstr

Returns the portion of string, or false if needle is not found.

If the strstr returns false, you add $b->link to the array, which might of type SimpleXMLElement.

You might cast it to a string (string)$b->link in that case.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement