2016-02-25 27 views
1

嘗試從<af:location>value</af:location>中獲取值。首先;是的,我已經搜索了很多的答案如何做。在這裏閱讀了很多關於Stackoverflow的問題並嘗試了很多代碼。但只是無法讓它工作。無法取出XML的名稱空間屬性

我不能顯示所有的嘗試我都做了,因爲我不記得所有的事情我試過了。

這裏是我使用的代碼的剝離版本:

$xml_dump = Feed::curl_file_get_contents($url); 

libxml_use_internal_errors(true); 

    if ($xml = simplexml_load_string($xml_dump)) 
    { 

    } 

我已經例如嘗試:

  • Namespace參數'af'在 - >simplexml_load_string($xml_dump, null, 0, 'af', true)
  • $xml->getNamespaces(true)
  • $sxe = new SimpleXMLElement($xml_dump); $namespaces = $sxe->getNamespaces(true);

但他們都沒有工作。

$xml_dump包含此:

<?xml version="1.0"?> 
<rss version="2.0" xmlns:af="http://www.example.se/rss"> 
    <channel> 
     <title>RSS Title - Example.se</title> 
     <link>http://www.example.se</link> 
     <description>A description of the site</description> 
     <pubDate>Wed, 24 Feb 2016 12:20:03 +0100</pubDate> 


       <item> 
        <title>The title</title> 
        <link>http://www.example.se/2.1799db44et3a9800024.html?id=233068</link> 
        <description>A lot of text. A lot of text. A lot of text.</description> 
        <guid isPermaLink="false">example.se:item:233068</guid> 

        <pubDate>Wed, 24 Feb 2016 14:55:34 +0100</pubDate> 
        <af:profession>16/5311/5716</af:profession> 
        <af:location>1/160</af:location> 

       </item> 
    </channel> 
</rss> 

解決了!

答案是:

$loc = $item->xpath('af:location'); 
echo $loc[0]; 
+0

您應該始終註冊您自己的Xpath前綴。像這樣:http://stackoverflow.com/a/24101080/2265374 – ThW

回答

1

的問題是不明確的,我不得不說。你提到過在問題開始時從前綴元素獲取值。但似乎試圖獲得一個命名空間,而不是每個嘗試的代碼。

「試圖從<af:location>value</af:location>走出價值」

如果你的意思是得到上述元素的值,那麼這是一個可能的方式:

$location = $xml->xpath('//af:location')[0]; 
echo $location; 

輸出:

1/160 

如果你的意思是讓空間URI的前綴名稱,而不是,然後使用getNamespaces()是要走的路:

echo $xml->getNamespaces(true)['af']; 

輸出:

http://www.example.se/rss 
+1

阿哈,然後我誤解了很多。現在學到了一些東西。然而,這是我想要的第一個例子。問題:該數組是整個Feed中所有「」的數組。或者我可以從每個'$ item-> xpath('// af:location')'獲取第一個/ [0]?你明白我的意思嗎? –

+0

我想你需要在開始時添加一個點,使XPath相對於當前的'$ item':'$ item-> xpath('.// af:location')'。至於直接孩子,你可以省略''''部分:'$ item-> xpath('af:location')'也是 – har07

+0

太棒了!謝謝! :d –

0

我們真的需要一個這是一個體面的典型答案,但我會在這裏重複一遍,因爲你搜索並沒有找到。答案非常簡單:你使用the children() method

這需要永久標識名稱空間的URI(推薦)或要解析的特定文檔中使用的前綴(如果該文件是自動生成的,可能會更改)。

在您的例子,我們有xmlns:af="http://www.example.se/rss",這樣我們就可以保存URI一個常數,以確定與一些有意義的命名空間給我們:

define('XMLNS_RSSAF', 'http://www.example.se/rss'); 

然後解析XML時,你穿越到item元素以正常的方式:

$xml = simplexml_load_string($xml_dump); 
foreach ($xml->channel->item as $item) { 
    // ... 
} 

而你通過指定命名空間得到的$item名稱空間的小孩:

$location = (string) $item->children(XMLNS_RSSAF)->location; 
相關問題