php – 如何使用SimpleXML获取带有命名空间的节点的属性?
youtube.xml
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gd="http://schemas.google.com/g/2005" xmlns:yt="http://gdata.youtube.com/schemas/2007"> <entry> ... <yt:duration seconds="1870"/> ... </entry> </feed> update_videos.php $source = 'youtube.xml'; // load as file $youtube = new SimpleXMLElement($source,null,true); foreach($youtube->entry as $item){ //title works echo $item->title; //now how to get seconds? My attempt... $namespaces = $item->getNameSpaces(true); $yt = $item->children($namespaces['yt']); $seconds = $yt->duration->attributes(); echo $seconds['seconds']; //but doesn't work :( } 解决方法
你在问题中得到的代码确实有效.您已经正确地编写了可以通过使用带有XML命名空间相关参数$ns和$is_prefix的
SimpleXMLElement::children() method来从不在默认命名空间中的namespaced-element访问属性作为根元素:
$youtube->entry->children('yt',TRUE)->duration->attributes()->seconds; // is "1870" 由于这与您在问题中的基本相同,可以说您已经回答了自己的问题.与扩展的Online Demo #2相比. 答案很长:你在问题中得到的代码确实有效.您可以在此处在线交互式示例中找到示例XML和代码:Online Demo #1 – 它显示了具有不同PHP和LIBXML版本的结果. 码: $buffer = '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:yt="http://gdata.youtube.com/schemas/2007"> <entry> <yt:duration seconds="1870"/> </entry> </feed>'; $xml = new SimpleXMLElement($buffer); echo "ibxml version: ",LIBXML_DOTTED_VERSION,"n"; foreach ($xml->entry as $item) { //original comment: how to get seconds? $namespaces = $item->getNameSpaces(true); $yt = $item->children($namespaces['yt']); $seconds = $yt->duration->attributes(); echo $seconds['seconds'],"n"; // original comment: but doesn't work. } echo "done. should read 1870 one time.n"; 结果: 输出为5.3.26,5.4.16 – 5.5.0 ibxml version: 2.9.1 1870 done. should read 1870 one time. 输出为5.3.15 – 5.3.24,5.4.5 – 5.4.15 ibxml version: 2.8.0 1870 done. should read 1870 one time. 输出为5.1.2 – 5.3.14,5.4.0 – 5.4.4 ibxml version: 2.7.8 1870 done. should read 1870 one time. 从这个角度看,一切都很好.由于您没有给出任何具体的错误描述,因此很难说您的案例出了什么问题.您可能正在使用在您提出问题时过时的PHP版本,例如收到致命错误:
可能也是由于过时的libxml版本.根据测试,以下libxml版本适用于PHP 5.1.2-5.5.0: > ibxml版本:2.9.1> ibxml版本:2.8.0> ibxml版本:2.7.8 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- php – Symfony2从具有ManyToMany关系的倒置实体获取对象
- php – WordPress数据库insert()和update() – 使用NULL值
- 使用php来提供CSS文件
- php中curl、fsocket、file_get_content三个函数的使用比较
- php中curl和file_get_content的区别
- php – 编辑图片/ inplace“moving”(一个Facebook个人资料
- PHP编程:php使用curl出现Expect:100-continue解决方法
- php – 如何从Gearman获取预定作业列表?
- 简介WordPress中用于获取首页和站点链接的PHP函数
- php下载文件源代码(强制任意文件格式下载)