本文来总结下使用PHP对xml 文件的内容进行操作,还有生成新的xml文件的方法。下面使用几个例子来说明。
新建xml文件:
$path = '/test/test.xml'; //文件路径
//查询文件是否存在
if (file_exists($path)) {
Error('文件已存在,不可新增');
return false;
} else {
比如想创建xml内容如下:
<?xml version="1.0" encoding="utf-8"?>
<!-- auto generated by System -->
<test>
<system>
<info name="name" value="name_value"/>
</system>
</test>
//新建xml文件,可以使用拼接的方式:
$content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- auto generated by System -->\n<test>\n";
$content .= " <". $data['tag_system'] .">\n";
$content .= " <". $data['tag_info'] ." name=\"".$data['name']."\" ";
$content .= "value=\"".$data['value']."\" ";
$content .= "/>\n";
$content .= " </". $data['tag_system'] .">\n";
$content .= "</test>\n";
$result = AddFile($path, $content);
if (!$result) {
Error('新增失败');
return false;
}
}
xml文件---新增内容(三种方式):
新增内容有多种方式,如果文件内容较短,比如想在某个标签中追加内容的话可以通过字符串匹配替换,也能使用simplexml函数、DOMDocument,推荐使用simplexml函数进行操作。
第一种方法(适用于文件比较小的情况):通过匹配字符串、替换字符串的方式
xml文件内容为:
<?xml version="1.0" encoding="utf-8"?>
<!-- auto generated by System -->
<test>
<system>
<info name="name" value="name_value"/>
</system>
</test>
**********代码如下**********
//读取文件内容
$content = ReadFile($path);
$str = "<system>\n";
$match = strstr($content, $str);
if($match){
$update = $str;
$update .= " <info name=\"".$data['name']."\" ";
$update .= "value=\"".$data['value']."\" ";
$update .= "/>\n";
}else{
//匹配不到 说明没有<system>标签,那就匹配<test>标签
$str = "<test>\n";
$update = $str;
$update .= " <system>\n";
$update .= " <info name=\"".$data['name']."\" ";
$update .= "value=\"".$data['value']."\" ";
$update .= "/>\n";
$update .= " </system>\n";
}
$content = str_replace($str, $update, $content);
$result = EditFile($path, $content);
-------------------------------------------------------
第二种方法,使用simplexml PHP5引进的SimpleXML,版本 >= PHP5即可使用
xml文件内容为:
<?xml version="1.0" encoding="utf-8"?>
<!-- auto generated by System -->
<system>
<info name="name" value="name_value"/>
</system>
**********代码如下**********
$xml = simplexml_load_file($path);
$new = $xml->addChild('info', null);
$new->addAttribute("name", 'test');
$new->addAttribute("value", '123');
$dom = new \DOMDocument("1.0", 'utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
file_put_contents($config_file, $dom->saveXML());
执行代码后:
<?xml version="1.0" encoding="utf-8"?>
<!-- auto generated by System -->
<system>
<info name="name" value="name_value"/>
<info name="test" value="123"/>
</system>
-------------------------------------------------------
第三种方法,使用DOMDocument
若如下xml文件内容,需要新增一个two节点
<?xml version="1.0" encoding="utf-8"?>
<one>
<two name="xiaoming" type="1">
<a test="test">test</a>
</two>
<one>
**********代码如下**********
$xml = new \DOMDocument("1.0", 'utf-8');
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true; //设置格式
$xml->load ($path); //加载xml文件
$oneNode = $xml->getElementsByTagName('one');//获取one元素节点
//添加注释
$msg = $xml->createComment("新增一行");
$oneNode->item(0)->appendChild($msg);
$twoNode = $xml->createElement('feature');//创建two元素节点
$name = $xml->createAttribute("name");
$twoNode->appendChild($name);
$nameValue = $xml->createTextNode("name-value");
$name->appendChild($nameValue);
$type = $xml->createAttribute("type");
$twoNode->appendChild($type);
$typeValue = $xml->createTextNode("type-value");
$type->appendChild($typeValue);
$a = $xml->createElement('a');//创建元素节点
$twoNode->appendChild($a);
$aTest = $xml->createAttribute('test');
$a->appendChild($aTest);
$aTestValue = $xml->createTextNode('test-value');
$aTest->appendChild($aTestValue);
$aNodeContent = $xml->createTextNode('test');//创建文本元素节点
$a->appendChild($aNodeContent);//在节点元素中添加文本元素节点
$oneNode->item(0)->appendChild($featureNode);//在one元素节点的最后添加two元素节点
$xml->save($path);//保存xml文件
执行代码后:
<?xml version="1.0" encoding="utf-8"?>
<one>
<two name="xiaoming" type="1">
<a test="test">test</a>
</two>
<!-- 新增一行 -->
<two name="name-value" type="type-value">
<a test="test">test</a>
</two>
<one>
xml文件---编辑内容:
若如下xml文件内容,需要编辑two节点的内容
<?xml version="1.0" encoding="utf-8"?>
<one>
<two name="xiaoming" type="1">
<a test1="test1">test</a>
</two>
<one>
//编辑
$xml = simplexml_load_file($path);
$update = $xml->addChild('two', null);
$update->addAttribute("name", $data['name']);
$update->addAttribute("type", $data['type']);
$a = $update->addChild('a',$data['test']); //$data['test'] 是a标签中的值
$a->addAttribute('test2', 'test2'); //<a test1="test1"> => <a test2="test2">
$domUpdate = dom_import_simplexml($update);
$t = $xml->xpath('//*[@name="xiaoming"]'); //查找匹配到含有name="xiaoming"的节点
if ($t) {
$domOriginal = dom_import_simplexml($t[0]);
$nodeUpdate = $domOriginal->ownerDocument->importNode($domUpdate, True);
$domOriginal->parentNode->replaceChild($nodeUpdate, $domOriginal); //替换掉之前的
}
$dom = new \DOMDocument("1.0", 'utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
$result = EditFile($path, $dom->saveXML());
if (!$result) {
Error('编辑失败');
}
return $result;
xml文件---删除内容:
$xml = simplexml_load_file($path);
$res = $xml->xpath('//*[@id="123"]'); //匹配查找含有 id="123" 的节点
if (count($res) > 0) {
$dom = dom_import_simplexml($res[0]);
$dom->parentNode->removeChild($dom);
}
$dom = new \DOMDocument("1.0", 'utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
$result = EditFile($path, $dom->saveXML());
xml文件---遍历修改内容:
若如下xml文件内容,需要将所有test节点的 id+1
<?xml version="1.0" encoding="utf-8"?>
<tags version="2">
<test id="0" pid="0" name="test1"/>
<test id="1" pid="0" name="test2"/>
</tags>
$xml = simplexml_load_file($path);
foreach ($xml->children()->test as $item){
$item->attributes()->id = $item->attributes()->id + 1;
}
$dom = new \DOMDocument("1.0", 'utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
$result = EditFile($path, $dom->saveXML());