How can i get to xml attribute of ?

2019-08-16 10:37发布

I can't figure out or find out how to parse the permission="allowed" value out of this xml, using PHP simplexml_load_file.

the basic structure is

<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:gd="http://schemas.google.com/g/2005" xmlns:yt="http://gdata.youtube.com/schemas/2007" gd:etag="W/&quot;DkEDSH47eCp7I2A9WhJbEEQ.&quot;">
<yt:accessControl action="comment" permission="allowed" />
<yt:accessControl action="commentVote" permission="allowed" />
<yt:accessControl action="videoRespond" permission="moderated" />
<yt:accessControl action="rate" permission="allowed" />
<yt:accessControl action="embed" permission="allowed" />
<yt:accessControl action="list" permission="allowed" />
<yt:accessControl action="autoPlay" permission="allowed" />
<yt:accessControl action="syndicate" permission="allowed" />

How can get to the value of the permission=allowed attribute on that last line?

2条回答
孤傲高冷的网名
2楼-- · 2019-08-16 11:00

This was so annoying to figure out...

(where $xml = simplexml_load_file($source); )

I'm able to get to the permission attribute with:

$xml->children('http://gdata.youtube.com/schemas/2007')->accessControl[4]->attributes()->permission;
查看更多
smile是对你的礼貌
3楼-- · 2019-08-16 11:06

You want to use XPath to retrieve records, it's an XML query language.

Please see the SimpleXMLElement's xpath() and registerXPathNamespace() methods. W3Schools explains XPath's syntax here.

For this XML

$xml = <<<EOD
<book xmlns:chap="http://example.org/chapter-title">
   <title>My Book</title>
</book>
EOD;

you'd register a namespace like this:

$sxe = new SimpleXMLElement($xml);
$sxe->registerXPathNamespace('c', 'http://example.org/chapter-title');
$result = $sxe->xpath('//c:title');
查看更多
登录 后发表回答