使用包含命名空间的PHP解析XML

时间:2011-03-29 21:48:40

标签: php xml

我正在尝试用PHP解析XML文件:

<post dsq:id="##Edited out##">
    <id />
    <message>##Edited out##</message>
    <createdAt>2010-07-09T16:08:44Z</createdAt>
    <author>
        <email>##Edited out##</email>
        <name>##Edited out##</name>
        <isAnonymous />
    </author>
    <ipAddress>##Edited out##</ipAddress>
    <thread dsq:id="##Edited out##" />
</post>

<post dsq:id="##Edited out##">
    <id />
    <message>##Edited out##</message>
    <createdAt>2010-07-09T16:10:07Z</createdAt>
    <author>
        <email>##Edited out##</email>
        <name>##Edited out##</name>
        <isAnonymous />
    </author>
    <ipAddress>##Edited out##</ipAddress>
    <thread dsq:id="##Edited out##" />
</post>

我使用简单的xml来解析它:

$xml = simplexml_load_file('disqus.xml');

foreach ( $xml->post as $post )
{
    echo $post['dsq:id'];
}

但是,我无法从post对象获取id属性:

<post dsq:id="##Edited out##">

非常感谢有关如何检索该信息的任何信息。

1 个答案:

答案 0 :(得分:1)

$xml = simplexml_load_file('disqus.xml');

foreach ( $xml->post as $post )
{
    $dsq = $post->children('disqus.com/disqus-internals'); //should this not have http://disqus.com/disqus-internals?
    echo $dsq->id;
}

您正在使用的那个w3.org/2001/XMLSchema-instance用于xsi名称空间。