2012-11-12 121 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