PHP - XML - Filtering XML Nodes by Namespace

Find only those nodes belonging to a particular namespace.

 

Use SimpleXML's children() method with the namespace URI (Universal Resource Identifier):

 

  1. <?php
  2. // define XML data string
  3. // containing namespaces
  4. $xmlData = <<< END
  5. <?xml version="1.0"?>
  6. <data xmlns:home="http://www.some.domain/xmlns/home" ↩
  7. xmlns:work="http://www.some.domain/xmlns/work">
  8.  <home:file>music.txt</home:file>
  9.  <work:file>accounts.dat</work:file>
  10.  <work:file>inbox.mbx</work:file>
  11.  <home:file>expenses.xls</home:file>
  12.  <home:file>addressbook.doc</home:file>
  13. </data>
  14. END;
  15. // read XML data
  16. $xml = simplexml_load_string($xmlData);
  17. // process nodes in "work" namespace
  18. // result: "accounts.dat inbox.mbx "
  19. foreach ($xml->children("http://www.some.domain/xmlns/work"as $file)
  20. {
  21.     echo "$file ";
  22. }
  23. ?>

Comments

It's easy to isolate only those child nodes belonging to a particular namespace if you're using SimpleXML: just pass the namespace URI to the children() method as an additional argument. In this example, this technique has been used to isolate all the nodes in the "work" namespace under the document element. The resulting node collection can then be processed in the usual manner, with a foreach() or other loop.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值