【问题标题】:XPATH Get Multiple Values within same Element in an RSS FeedXPATH 获取 RSS 提要中同一元素内的多个值
【发布时间】:2013-01-12 03:10:22
【问题描述】:

我有一个格式如下的 RSS 源:

<item>
     <posturl>mysite.com/abc.html</posturl>
     <imagepath>123.jpg</imagepath>
</item>
<item>
     <posturl>mysite.com/def.html</posturl>
     <imagepath>456.jpg</imagepath>        
</item>
<item>
     <posturl>mysite.com/ghi.html</posturl>
     <imagepath>789.jpg</imagepath>    
</item>

我有一个脚本,我想在其中提取上述两个值。我可以提取其中一个值并使用以下代码构建 html 代码:

<?php
     $xml = simplexml_load_file('http://myrssfeed.com');
     $imgs = $xml->xpath('//imagepath');
            echo '<ul>';
         foreach($imgs as $output1) {
            echo '<li><img src="' . $output1 . '" ></li>';
            }

            echo '</ul>';
 ?>

感谢这里的人们提供的所有帮助,这就像一个魅力。但我需要扩展该 second 回声线以读取如下内容:

echo  '<li><a href="' . $output2 . '"><img src="' . $output1 . '" ></a></li>';

我需要有关如何在与 $output1 相同的项目中提取 $output2 = posturl 的帮助。

基本上我需要将图像显示为链接... imagepath 和 posturl 都是 item 中的元素。

非常感谢。

【问题讨论】:

    标签: php xpath xml-parsing foreach rss


    【解决方案1】:

    您可以选择&lt;item&gt; 元素而不是&lt;posturl&gt;&lt;imagepath&gt;。像这样:

    $xml = simplexml_load_file('http://myrssfeed.com');
    
    echo '<ul>';
    
    foreach($xml->xpath('//item') as $item) { 
        printf('<li><a href="%s"><img src="%s" /></a></li>', 
            $item->posturl, $item->imagepath); 
    }
    
    echo '</ul>';
    

    【讨论】:

    • 真棒...完美运行。我连续试了一整天....非常感谢您的帮助!!!
    • 抱歉还有一个问题...我有第三个项目(感谢您)我想出了如何添加到 printf...但是如果我想消除其中的所有句点怎么办结果并用空格替换它们...再次感谢您。
    • 使用$result = str_replace('.', ' ',$result); 替换句点。
    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 2018-05-01
    • 2022-08-17
    • 2014-10-17
    相关资源
    最近更新 更多