PHP如何读取xml文件?

准备xmlwen文件:a.xml

<?xml version="1.0" encoding="UTF-8"?>
<humans>

<zhangying>
<name>张映</name>
<sex>男1</sex>
<old1>280</old1>
</zhangying>

<tank>
<name>tank</name>
<sex></sex>
<old1>28</old1>
</tank>

</humans>

 

1.simplexml读取xml

 

<?php
header("content-type:text/html;charset=utf-8");
$xml_array=simplexml_load_file('a.xml'); //将XML中的数据,读取到数组对象中
foreach($xml_array as $tmp){

echo $tmp->name."-".$tmp->sex."-".$tmp->old1."<br>";
}

?>
如果你使用 curl 获取的 xml data
$xml = simplexml_load_string($data);
$data['tk'] = json_decode(json_encode($xml),TRUE);
如果是直接获取 URL 数据的话
$xml = simplexml_load_file($data);
$data['tk'] = json_decode(json_encode($xml),TRUE);
先把 simplexml 对象转换成 json,再将 json 转换成数组。

xmlreader来读取xml数据

 

<?php
header("content-type:text/html;charset=utf-8");
$reader = new XMLReader();
$reader->open('a.xml'); //读取xml数据
$i=1;

while ($reader->read()) { //是否读取
if ($reader->nodeType == XMLReader::TEXT) { //判断node类型
if($i%3){
echo $reader->value."__"; //取得node的值
}else{
echo $reader->value."<br>" ;
}
$i++;
}
}

?>

 

 

 

 

posted @ 2016-02-14 16:48  侠岚之弋痕夕  阅读(618)  评论(0编辑  收藏  举报
Where is the starting point, we don't have a choice, but the destination where we can pursue!