标签:int nod 西游 reac node new else ice 显示
XML 的设计宗旨是传输数据,而非显示数据。因为需要读取其中数据。我们通常对数组的操作非常熟悉我们可将xml解析完当成数组处理。
<?xml version="1.0" encoding="utf-8"?>
<books>
<item>
<title>三国</title>
<price>30.33</price>
<author>
<name>李健</name>
</author>
</item>
<item>
<title>西游</title>
<price>25.55</price>
<author>lijian</author>
</item>
<item>
<title>红梦</title>
<price>14.44</price>
<author>lijian</author>
</item>
</books>
以下是php内容
<?php
//读取xml
$xml=simplexml_load_file("2.xml");
print_r($xml);
function toArray($sim) {
$arr = (array) $sim;
foreach($arr as $k=>$v) {
if($v instanceof simplexmlelement || is_array($v)) { //可以更换为is_object($v)
$arr[$k] = toArray($v);
}
}
return $arr;
}
$arr = toArray($xml);
print_r($arr);
exit;
这里附上另一种转数组方法
<?php
$xml = simplexml_load_file(‘2.xml‘);
$xml = json_decode(json_encode($xml), true);
print_r($xml);
exit;
数组转回xml方式
<?php
$arr = array (
‘item‘ =>
array (
0 =>
array (
‘title‘ => ‘三国‘,
‘price‘ => ‘30.33‘,
‘author‘ =>
array (
‘name‘ => ‘李健‘,
),
),
1 =>
array (
‘title‘ => ‘西游‘,
‘price‘ => ‘25.55‘,
‘author‘ => ‘lijian‘,
),
2 =>
array (
‘title‘ => ‘红梦‘,
‘price‘ => ‘14.44‘,
‘author‘ => ‘lijian‘,
),
),
);
function arr2xml($arr,$node=null){
if($node === null){
$simxml = new simpleXMLElement(‘<?xml version="1.0" encoding="utf-8"?><root></root>‘);
}else{
$simxml = $node;
}
foreach($arr as $k=>$v){
if(is_numeric($k)){
$k = ‘item‘;
}
if(is_array($v)){
arr2xml($v,$simxml->addChild($k));
}else{
$simxml->addChild($k,$v);
}
}
return $simxml->saveXML();
}
header(‘content-type:text/xml‘);
echo arr2xml($arr);
exit;
标签:int nod 西游 reac node new else ice 显示
原文地址:https://www.cnblogs.com/zyfbk/p/8900482.html