duanpiyao2734 2011-05-14 06:38
浏览 88
已采纳

将来自多个XML节点的数据混合到一个PHP变量中

I am trying to find out how to merge the FIPS part of this XML file into one php variable with SimpleXML.

a sample xml file I'm trying to use is at http://codepad.org/MQeR2VBZ

basically i want a variable with "001033,001077" in it (without the quotes"

I'm new to PHP and this is my first time using stackoverflow so please forgive me if I'm full of fail

  • 写回答

2条回答 默认 最新

  • doulun5683 2011-05-14 08:24
    关注

    You can solve this easily with XPath.

    XPath lets you query for nodes in the document in almost any possible combination. To query for the geocode value that is preceded by a valueName element with the content FIPS6, you can use this query:

    /alert/info/area/geocode/value[preceding-sibling::valueName = "FIPS6"]
    

    However, the document has a default namespace for the alert element (as indicated by the xmlns attribute). By default, SimpleXml will not be able to access any namespaced nodes in the document via XPath until we tell it the namespace via registerXPathNamespace and prefix any elements in the query with an arbitrary prefix.

    The result of the XPath will be an array containing SimpleXmlElements. When you cast a SimpleXmlElement to string (or use it in a string context), it will return it's nodeValue, which is the values you actually want to combine, so you can simply call implode on the resulting array to combine the values into a string.

    Code (demo)

    $alert = simplexml_load_file('http://…');
    $alert->registerXPathNamespace('a', 'urn:oasis:names:tc:emergency:cap:1.1');
    $fipsValues = implode(',', $alert->xpath(
        '/a:alert/a:info/a:area/a:geocode/a:value[
            preceding-sibling::a:valueName = "FIPS6"
        ]'
    ));
    print_r($fipsValues); // will contain "001033,001077"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载