duanpu5048 2014-06-05 11:04
浏览 121

使用php解析嵌套的xml

Hello i am trying to parse nested xml but i am using multiple for loops to extact but i dont find it very proper way.

I want to parse data based on unique id and separte them but cant figure any easy way to that

here is my 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>

Here is my code

<?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条回答 默认 最新

  • dongxi1680 2014-06-05 11:18
    关注

    Try this:

    $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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000