2016-11-14 91 views
1

我有下面的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="Faktencheck: Keine Werftführungen vor 2017" /> 
    <psc:chapter start="00:02:12.135" title="Sea Life Timmendorfer Strand"" /> 

我需要拿到冠军,并开始属性。 我已经设法获得的元素:

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

的输出是一样的东西:

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

当我现在遵循的答案在这里SO多个问题得到@属性:

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

我刚收到一个空的结果。

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

SimpleXMLElement Object 
(
) 
+2

你已经得到了正确的答案,但澄清:属性是不是在一个命名空间 - 只用一个前缀属性可以在一个命名空间(不像元素节点)。此外,我建议使用实际的命名空间,而不是别名/前缀:'$ x-> children('http://podlove.org/simple-chapters');' – ThW

回答

2

您需要从章得到你的属性。

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

你的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> 

PHP代码:

$x = simplexml_load_string($xmlString); 
$chapters=$x->children('psc', true); 

foreach ($chapters->chapter as $chapter) { 
    echo $chapter->attributes()->{'start'}; 
} 
+1

缺少的结束标记仅仅是我的错误,因为我不想在这里粘贴整个100行的xml。你的代码是正确的,但是,我只是使用了错误的对象($ unter而不是$ chapter),就像mim发现的那样。 –