Ole Albers Ole Albers - 4 months ago 29
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:

$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
$chapters=$x->children('psc', true);

foreach ($chapters as $chapter) {

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.

returns an empty object:

SimpleXMLElement Object


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;