php用simplexml来操作xml

<?php

$username = 'zhansan';

if (!file_exists('001.xml'))
{
$fp = fopen('001.xml', 'w');
$xmlContent = '<?xml version="1.0" encoding="utf-8"?><record></record>';
fwrite($fp, $xmlContent);
fclose($fp);

$xml = simplexml_load_file('001.xml');
$unode = $xml->addChild($username);
$unode->addChild('times', 2);
$unode->addChild('time', '2016');
$unode->addChild('ip', '192.1.0.11');


$unode = $xml->addChild('lisi');
$unode->addChild('times', 22);
$unode->addChild('time', '2016');
$unode->addChild('ip', '12.0.0.13');

$xml->asXML('001.xml');
}
//修改
$xml = simplexml_load_file('001.xml');
echo $xml;
$usr = $xml->lisi;
$usr->times += 1;
echo $usr->times;
$xml->asXML('001.xml');

/**
* 删除
*/
//unset($xml->zhansan);
//$xml->asXML('001.xml');

//查看


//删除xml文件
//unlink('001.xml');



echo '<br />';
/**
* 查看xml,不一定好
*/
//$dom = simplexml_import_dom($xml);
echo $dom->zhansan->times.'<br />';

if ($dom->saonv->times === null)
{
echo 'saop is not exist';
}
echo '<br />';
var_dump($xml->lisis->times);

/**
* 将xml转为数组 ,注意,如果有顶级同名节点会被合并
*/
$jn = json_encode($xml);
$data = json_decode($jn, true);

echo '<pre>';
print_r($data['xml']['node']);
echo '</pre>';




?>
posted @ 2016-11-10 15:43  yubolin  阅读(180)  评论(0编辑  收藏  举报