2012-11-12 104 views
1

我使用下面的函數如何遍歷XML在PHP

function file_get_contents_curl($url) { 
    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);  

    $data = curl_exec($ch); 
    curl_close($ch); 

    return $data; 
} 
$myTestingUrl = file_get_contents_curl("myUrl"); 

我運行的功能我有

$myTestingUrl = 
<?xml version="1.0" encoding="UTF-8"?> 
<map> 
    <entry key="keyName"> 
     <entry key="ActionUrl">http://www.my_actionUrl.com/</entry> 
    </entry> 
</map> 

能否請你告訴我,我怎麼可以遍歷$ myTestingUrl拿到後入門鍵「ActionUrl」(http://www.my_actionUrl.com/)中的一個變量在php中的內容?

謝謝!

+0

可能重複[在PHP中遍歷XML](http://stackoverflow.com/questions/6301084/traversing-xml-in-php) – ajreal

回答

4

嘗試

$xml = simplexml_load_string($myTestingUrl); 
$items = $xml->xpath('/map/entry/entry[@key="ActionUrl"]/text()'); 
echo $items[0]; 
+0

好的!這裏是[simpleXML](http://www.w3schools.com/php/php_xml_simplexml.asp)的更多信息 – VDP

+0

在最後一行我收到以下錯誤:注意:未定義索引:0 – octasimo

+0

將代碼從http:/ /eval.in/2767並嘗試它是否工作。如果它正在工作,那麼'echo'你的xml並檢查它是否有區別。 – air4x

2

我喜歡@ air4x的XPath的方法,但在這裏它是沒有的XPath - 用於顯示元素的用途和屬性的訪問中SimpleXML

Codepad demo

$obj = simplexml_load_string($myTestingUrl); 

foreach($obj->entry as $entry) 
{ 
    if(isset($entry->entry)) 
    { 
     foreach($entry->entry->attributes() as $key => $value) 
     { 
      if($key == 'key' && $value == 'ActionUrl') 
      { 
       echo 'ActionUrl is: ' . (string)$entry->entry; 
       break 1; 
      } 
     } 
    } 
} 
+0

我得到一個空白頁面,沒有回答這個。我做了以下步驟: 'echo $ myTestingUrl; (輸出<?xml version =「1.0」encoding =「UTF-8」?> http://urlllll/library.xml) $ obj = simplexml_load_string($ myTestingUrl); ($ obj-> entry as $ entry){ if(isset($ entry-> entry)){ foreach($ entry-> entry-> attributes()as $ key => $ value){ if ($ key =='key'&& $ value =='ActionUrl'){ \t echo'ActionUrl is:'。 (字符串)$入門>項; \t break 1; } } } }' – octasimo

+0

@CSSensei您必須在其他代碼中出現錯誤,此代碼才能正常工作(如在鍵盤演示中所見)。看看你的錯誤日誌。 – MrCode

+0

我的頁面上沒有其他代碼,只是爲了測試它。 在鍵盤上有修飾功能。這是強制性的提取工作? – octasimo