使用php解析嵌套的xml

时间:2014-06-05 11:04:12

标签: php xml parsing

您好我正在尝试解析嵌套的xml但是我使用多个for循环来接触但是我没有找到它非常正确的方法。

我想根据唯一ID解析数据并将它们分开,但无法轻易找到它

这是我的xml

<propertyList date="2014-06-02-17:30:33" username="adsss" password="v147C0z5CBlw">

<business modTime="2014-06-02-12:22:32" status="current">

<agentID>TEST</agentID>

<uniqueID>1420648</uniqueID>

<listingAgent id="1">

<name>jonny</name>

<telephone type="BH"></telephone>

<telephone type="mobile"></telephone>

<email>aT@cs.com.au</email>

</listingAgent>

<listingAgent id="2"></listingAgent>


</business>

<business modTime="2014-05-16-15:11:41" status="current">

<agentID>TEST</agentID>

<uniqueID>1435201</uniqueID>

<listingAgent id="1">

<name>Mike Smith</name>

<telephone type="BH"></telephone>

<telephone type="mobile"></telephone>

<email>acebrokers@bs.com.au</email>

</listingAgent><listingAgent id="2"></listingAgent>

</business>



</propertyList>

这是我的代码

<?php
$xml=simplexml_load_file("myxmldata.xml");
echo "<pre>";


for($i=0;$i<count($xml);$i++):

echo "agentID=>".$xml->business[$i]->agentID;

echo "<br>";

echo "uniqueID=>".$xml->business[$i]->uniqueID;

echo "<br>";

endfor;


for($i=0;$i<count($xml->business->listingAgent);$i++):

  echo "agentName=>".$xml->business->listingAgent[$i]->name;

endfor;

for($i=0;$i<count($xml->business->listingAgent->telephone);$i++):

  echo "telephonetype=>".$xml->business->listingAgent->telephone[$i]->type;

endfor;


?> 

1 个答案:

答案 0 :(得分:0)

试试这个:

$xml = simplexml_load_file("myxmldata.xml");

$data = array();
foreach($xml->business as $business) {
    $business = (array) $business;
    if (!array_key_exists($business['uniqueID'], $data)) {
        $listingAgent = (array) $business['listingAgent'];
        $data[$business['uniqueID']] = array(
            'agentID' => $business['agentID'],
            'uniqueID' => $business['uniqueID'],
            'name' => (string)$listingAgent[0]->name,
            'telephone' => (string) $listingAgent[0]->telephone[0],
            'mobile' => (string) $listingAgent[0]->telephone[1],
            'email' => (string) $listingAgent[0]->email,
        );
    }
}
var_dump($data);