2016-11-14 92 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發現的那樣。 –