Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 无法从具有自定义命名空间的XML文件中获取属性_Php_Xml - Fatal编程技术网

Php 无法从具有自定义命名空间的XML文件中获取属性

Php 无法从具有自定义命名空间的XML文件中获取属性,php,xml,Php,Xml,我有以下XML结构: <?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=

我有以下XML结构:

<?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"" />
输出类似于:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [start] => 00:00:12.135
            [title] => Begrüßung
        )    
)
当我现在按照这里的答案来回答多个问题以获得@attributes:

echo $unter->attributes()["start"];
我只收到一个空的结果

(更新)
print\r($unter->attributes())
返回一个空对象:

SimpleXMLElement Object
(
)

必须像对象一样使用元素,而不是数组:

echo $unter->attributes()->start;
更多信息请参见:

您的xml格式错误(结束章节标记)。我修改了您的xml和php代码(阅读章节标记),如下格式所示。现在它的工作完美

XML字符串:

<?xml version="1.0" encoding="UTF-8"?>
<psc:chapters xmlns:psc="http://podlove.org/simple-chapters" version="1.2">
   <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" />
</psc:chapters>

你需要从第章中获得你的属性

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;
    }
}

也不管用$unter->attributes()似乎是一个空对象缺少结束标记只是我的错误,因为我不想在这里粘贴整个100行xml。您的代码是正确的,但是,我只是使用了错误的对象($unter而不是$chapter),就像mim发现的那样。您已经得到了正确的答案,但要澄清的是:属性不在名称空间中-只有带有前缀的属性可以在名称空间中(与元素节点不同)。此外,我建议使用实际名称空间,而不是别名/前缀:
$x->children('children')http://podlove.org/simple-chapters');
$x = simplexml_load_string($xmlString);
$chapters=$x->children('psc', true);

foreach ($chapters->chapter as $chapter) {
    echo $chapter->attributes()->{'start'};
}
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;
    }
}