php函数——『解析 xml数据』

<?php

//该文件是
//$raw_post_data = file_get_contents('php://input');
//file_put_contents('a.txt', $raw_post_data, FILE_APPEND);
//首先掌握 xml操作数据
$data = <<<XML
<?xml version="1.0" encoding="utf-8" ?>
<Cdr id="1920150803154502-0">
  <callid>8216</callid>
  <outer id="24" />
  <TimeStart>20150803154311</TimeStart>
  <Type>OU</Type>
  <Route>IP</Route>
  <CPN>338</CPN>
  <CDPN>053286677735</CDPN>
  <TimeEnd>20150803154502</TimeEnd>
  <Duration>96</Duration>
  <TrunkNumber>568116939</TrunkNumber>
  <Recording>20150803/338_053286677735_20150803-154326_8216</Recording>
</Cdr>
XML;
echo '<pre>';
$xml_obj = simplexml_load_string($data); //创建 SimpleXML对象
//获取跟节点的名称
echo $xml_obj->getName() . '<br>';
//获取跟节点下面的元素信息
foreach ($xml_obj->children() as $child) {
    $attribute = '';
    //获取子元素的名称
    $name = $child->getName();
    //循环获取子元素的属性信息 
    foreach ($child->attributes() as $k => $v) {
        $prefix = empty($attribute) ? $attribute : $attribute . ',';
        $attribute = $prefix . "{$k}:{$v}";
    }
    $att = empty($attribute) ? '' : "属性:$attribute";
    echo $name . ':' . $child . $att . '<br>';
}
print_r($xml_obj); //输出 XML
?> 

 

posted @ 2015-08-03 16:43  timelesszhuang  阅读(310)  评论(0编辑  收藏  举报