Ole Albers Ole Albers - 25 days ago 9
PHP Question

Cannot get Attributes from XML-file with custom namespace

I have the following XML-Structure:

<?xml version="1.0" encoding="utf-8"?>
<psc:chapters version="1.2" xmlns:psc="http://podlove.org/simple-chapters">
<psc:chapter start="00:00:12.135" title="Begrüßung" />
<psc:chapter start="00:00:20.135" title="Faktencheck: Keine Werftführungen vor 2017" />
<psc:chapter start="00:02:12.135" title="Sea Life Timmendorfer Strand"" />


I need to get the title and start attribute.
I already managed to get to the elements:

$feed_url="http://example.com/feed.psc";
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
$chapters=$x->children('psc', true);

foreach ($chapters as $chapter) {
$unter=$chapter->children();
print_r($unter);
}


The output is something like:

SimpleXMLElement Object
(
[@attributes] => Array
(
[start] => 00:00:12.135
[title] => Begrüßung
)
)


When I now follow the answers here on SO to multiple questions to get the @attributes:

echo $unter->attributes()["start"];


I just receive an empty result.

(Update)
print_r($unter->attributes())
returns an empty object:

SimpleXMLElement Object
(
)

Answer

You need to get your attributes from chapter.

foreach ($chapters as $chapter) {
    // You can directly read them 
    echo $chapter->attributes()->{'title'}

    // or you can loop them
    foreach ($chapter->attributes() as $key => $value) {
        echo $key . " : " . $value;
    }
}