PHP - 如何读取此XML文件

时间:2013-09-17 21:47:44

标签: php xml

我有以下xml:

<CallOverview>
    <Calls Count="2">
        <Call CallType="LandLine" Customer="this account" StartTime="2013-09-17 20:21:19 (UTC)" Destination="NL" Duration="00:00:05" Charge="0.045" CallId="158263673"/>
        <Call CallType="Mobile" Customer="this account" StartTime="2013-09-17 20:18:34 (UTC)" Destination="US" Duration="00:00:26" Charge="0.101" CallId="158263381"/>
    </Calls>
<MoreData>No more data available</MoreData>
</CallOverview>

我像这样检索XML:

function get_xml($url)
{ 
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
};

我根据需要收到了XML,但我无法以正确的方式提取数据:

$xml=simplexml_load_string ( get_xml($url_post) ) ;

echo $xml->getName() . "<br>";

foreach($xml->children() as $child)
{
    echo $child->getName() . ": " . $child . "<br>";

    foreach($child->children() as $subchild)
    {
        echo $subchild->getName() . ": " . $subchild . "<br>";
        $role = array($subchild->attributes());

        foreach($subchild as $key => $value) {
            echo "$role $key $value";            
        }
    }
}

我得到以下结果:

Calls: 
Call: 
Call:
MoreData: No more data available

我试过了:

foreach($xml->Call[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}

但是我收到以下错误:

Fatal error: Call to a member function attributes() on a non-object

此外,当没有进行任何通话时,没有Call元素。 xml的新手,所以不确定我是否可以使用子项下的子项。

1 个答案:

答案 0 :(得分:0)

最后我使用了DOM解析器:

$dom_document = new DOMDocument();

$dom_document->loadXML(get_xml($url));

$searchNode = $dom_document->getElementsByTagName( "Call" );

if (!is_null($searchNode)) {
foreach( $searchNode as $searchNode )
{
    $Destination = $searchNode->getAttribute('Destination');
echo "$Destination";
}
}