版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/youcijibi/article/details/87904774
1,simplexmlobject对象内置了__toString()魔术方法所以xml的对象属性可以直接echo 或者可以被(string)xmlobject 强制类型转换为string类型,下面代码有演示及说明。
<?php
class Conf
{
private $_file;
private $_xml;
private $_lastMatch;
public function __construct($file)
{
$this->_file = $file;
$this->_xml = simplexml_load_file($file);
}
public function Write()
{
file_put_contents($this->_file, $this->_xml->asXML());
}
public function Get($str)
{
$matches = $this->_xml->xpath("/conf/item[@name=\"$str\"]");
if (count($matches)) {
$this->_lastMatch = $matches[0]; //对象的引用传递,只有经过这一步才会使下面的(set)值生效,如果这里赋值为$matches则不行,因为它是个数组不是对象
return $matches;
}
return null;
}
public function Set($key, $value)
{
if (!is_null($this->Get($key))) {
$this->_lastMatch[0] = $value; //对象的引用传递,在Get方法中$this->_lastMatch被赋值为$matches[0]这个对象,所以这里修改$this->_lastMatch中的值时$matches[0]这个对象也会被改变
return;
}
$conf = $this->_xml->conf;
// var_dump($conf);die;
$conf->addChild('item', $value)->addAttribute('name', $key);
}
}
$conf = new Conf(dirname(__FILE__) . '/test.xml');
//$user = $conf->Get('user');
//var_dump( $user );
//$new_user = $conf->Set('user', 'LiLy'); //值被修改为LiLy
//$user = $conf->Get('user');
//echo $user; 虽然$user是一个对象但是其内置了__tostring方法所以可以直接echo
//var_dump( $user );
//var_dump($user);
//var_dump((string)$conf);
$conf->Set('gender1', 'boy');
//$conf->Write();