简体   繁体   English

使用 simplexml 修改从 rss 文件中提取的数据

[英]Modify data extracted from rss file with simplexml

I am extracting data from an rss file using simplexml.我正在使用 simplexml 从 rss 文件中提取数据。 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.为了能够使用这些数据,我需要在这些 url 中删除“base”一词之前的所有内容。

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.但它看起来很乱,我很确定有一种方法可以更有效地做到这一点,而不必一遍又一遍地调用 strstr function。

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?还是我对此完全错了?

in the top example you are iterate over the items... in the foreach you are tying it iterate over links在上面的示例中,您正在迭代项目...在 foreach 中,您正在将其绑定在链接上

Using foreach($rss->channel->item->link as $b) will give the link in $b使用foreach($rss->channel->item->link as $b)将给出$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请注意,使用strstr

Returns the portion of string, or false if needle is not found.返回字符串的一部分,如果没有找到 needle,则返回 false。

If the strstr returns false, you add $b->link to the array, which might of type SimpleXMLElement .如果 strstr 返回 false,则将$b->link添加到可能是SimpleXMLElement类型的数组中。

You might cast it to a string (string)$b->link in that case.在这种情况下,您可以将其转换为字符串(string)$b->link

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM