0

我有以下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

同样,当没有调用时,没有调用元素。xml 的新手,所以不确定我是否可以在 child 下使用 child。

4

1 回答 1

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";
}
}
于 2013-09-18T17:36:59.820 回答