<?php
/**
* How to get attribute of node with namespace using SimpleXML?
*
* @link http://stackoverflow.com/q/6576773/367456
*/
$buffer = '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:yt="http://gdata.youtube.com/schemas/2007">
<entry>
<yt:duration seconds="1870"/>
</entry>
</ns: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";
Warning: SimpleXMLElement::__construct(): Entity: line 5: parser error : Opening and ending tag mismatch: feed line 1 and ns:feed in /in/sokIA on line 13
Warning: SimpleXMLElement::__construct(): </ns:feed> in /in/sokIA on line 13
Warning: SimpleXMLElement::__construct(): ^ in /in/sokIA on line 13
Fatal error: Uncaught Exception: String could not be parsed as XML in /in/sokIA:13
Stack trace:
#0 /in/sokIA(13): SimpleXMLElement->__construct('<feed xmlns="ht...')
#1 {main}
thrown in /in/sokIA on line 13
Process exited with code 255.
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Warning: SimpleXMLElement::__construct(): Entity: line 5: parser error : Opening and ending tag mismatch: feed line 1 and ns:feed in /in/sokIA on line 13
Warning: SimpleXMLElement::__construct(): </ns:feed> in /in/sokIA on line 13
Warning: SimpleXMLElement::__construct(): ^ in /in/sokIA on line 13
Fatal error: Uncaught Exception: String could not be parsed as XML in /in/sokIA:13
Stack trace:
#0 /in/sokIA(13): SimpleXMLElement->__construct('<feed xmlns="ht...')
#1 {main}
thrown in /in/sokIA on line 13
Process exited with code 255.
Output for 5.6.0 - 5.6.40
Warning: SimpleXMLElement::__construct(): Entity: line 5: parser error : Opening and ending tag mismatch: feed line 1 and ns:feed in /in/sokIA on line 13
Warning: SimpleXMLElement::__construct(): </ns:feed> in /in/sokIA on line 13
Warning: SimpleXMLElement::__construct(): ^ in /in/sokIA on line 13
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /in/sokIA:13
Stack trace:
#0 /in/sokIA(13): SimpleXMLElement->__construct('<feed xmlns="ht...')
#1 {main}
thrown in /in/sokIA on line 13
Process exited with code 255.