更改XML节点元素值并保存文件
问题描述:
<testimonials>
<testimonial id="4c050652f0c3e">
<nimi>John</nimi>
<email>[email protected]</email>
<text>Some text</text>
<active>1</active>
</testimonial>
<testimonial id="4c05085e1cd4f">
<name>ats</name>
<email>[email protected]</email>
<text>Great site!</text>
<active>0</akctive>
</testimonial>
</testimonials>
我有这样的XML晶格结构,我需要找到特定的标识和变化其值一个证明并保存文件。 我有一个PHP脚本根据其ID删除特定的告别赛:更改XML节点元素值并保存文件
<?php
$xmlFile = file_get_contents('test.xml');
$xml = new SimpleXMLElement($xmlFile);
$kust_id = $_GET["id"];
foreach($xml->testimonial as $story) {
if($story['id'] == $kust_id) {
$dom=dom_import_simplexml($story);
$dom->parentNode->removeChild($dom);
$xml->asXML('test.xml');
header("Location: newfile.php");
}
}
?>
答
您可以使用XPath找到特定元素。 SimpleXMLElement->xpath()返回(匹配)SimpleXMLElement对象数组,即您可以访问和更改每个元素的数据,就像在“您的”foreach循环中一样。
<?php
// $testimonials = simplexml_load_file('test.xml');
$testimonials = new SimpleXMLElement('<testimonials>
<testimonial id="4c050652f0c3e">
<nimi>John</nimi>
<email>[email protected]</email>
<text>Some text</text>
<active>1</active>
</testimonial>
<testimonial id="4c05085e1cd4f">
<name>ats</name>
<email>[email protected]</email>
<text>Great site!</text>
<active>0</active>
</testimonial>
</testimonials>');
// there can be only one item with a specific id, but foreach doesn't hurt here
foreach($testimonials->xpath("testimonial[@id='4c05085e1cd4f']") as $t) {
$t->name = 'LALALA';
}
echo $testimonials->asXML();
// $testimonials->asXML('test.xml');
打印
<?xml version="1.0"?>
<testimonials>
<testimonial id="4c050652f0c3e">
<nimi>John</nimi>
<email>[email protected]</email>
<text>Some text</text>
<active>1</active>
</testimonial>
<testimonial id="4c05085e1cd4f">
<name>LALALA</name>
<email>[email protected]</email>
<text>Great site!</text>
<active>0</active>
</testimonial>
</testimonials>
+1
XPath的+1。我有同样的想法,但我不知道应该改变哪个值。 – 2010-06-02 10:19:51
什么是告别赛的价值?它有4个孩子,你想改变什么? – 2010-06-02 10:05:40