dtvnnhh8992 2011-04-30 01:03
浏览 49
已采纳

PHP XML文件过滤器匹配

I am having a heck of a time getting this working...

What I want to do is filter a xml file by a city (or market in this case).

This is the xml data.

<itemset>
<item>
<id>2171</id>
<market>Vancouver</market>
<url>http://</url></item>
<item>
<id>2172</id>
<market>Toronto</market>
<url>http://</url></item>
<item>
<id>2171</id>
<market>Vancouver</market>
<url>http://</url></item>

This is my code...

<?php
$source = 'get-xml-feed.php.xml';

$xml = new SimpleXMLElement($source);

$result = $xml->xpath('//item/[contains(market, \'Toronto\')]');

while(list( , $node) = each($result)) {
    echo '//Item/[contains(Market, \'Toronto\')]',$node,"
";
}

?>

If I can get this working I would like to access each element, item[0], item[1] base on filtered results.

Thanks

  • 写回答

3条回答 默认 最新

  • donglaoe2979 2011-04-30 01:26
    关注

    I think this implements what you are looking for using XPath:

    <?php
    $source = file_get_contents('get-xml-feed.php.xml');
    
    $xml = new SimpleXMLElement($source);
    
    foreach ($xml as $node)
    {
        $row = simplexml_load_string($node->asXML());
        $result = $row->xpath("//item/market[.='Toronto']");
        if ($result[0])
        {
            var_dump($row);
        }
    }
    
    ?>
    

    As another answer mentioned, unless you are wed to the use of XPath it's probably more trouble than it's worth for this application: just load the XML and treat the result as an array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)