如何在php中遍历xml

时间:2012-11-12 12:51:55

标签: php xml xml-parsing

我正在使用以下功能

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以获取php中变量的输入键“ActionUrl”(http://www.my_actionUrl.com/)的内容?

谢谢!

2 个答案:

答案 0 :(得分:3)

尝试

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

答案 1 :(得分: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;
            }
        }
    }
}