在PHP中更改XML节点元素值并保存文件

Han*_*nes 6 php xml dom

<testimonials>
    <testimonial id="4c050652f0c3e">
        <nimi>John</nimi>
        <email>test@test.com</email>
        <text>Some text</text>
        <active>1</active>
        </testimonial>
    <testimonial id="4c05085e1cd4f">
        <name>ats</name>
        <email>some@test.ee</email>
        <text>Great site!</text>
        <active>0</akctive>
    </testimonial>
</testimonials>
Run Code Online (Sandbox Code Playgroud)

我有这个XML strcuture,我需要找到一个具有特定id的推荐,并更改并保存文件.我有一个PHP脚本根据其ID删除特定的推荐:

<?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");
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

Vol*_*erK 17

您可以使用XPath查找特定元素.SimpleXMLElement-> xpath()返回(匹配)SimpleXMLElement对象的数组,即您可以像访问"your"foreach循环一样访问和更改每个元素的数据.

<?php
// $testimonials = simplexml_load_file('test.xml');
$testimonials = new SimpleXMLElement('<testimonials>
    <testimonial id="4c050652f0c3e">
        <nimi>John</nimi>
        <email>test@test.com</email>
        <text>Some text</text>
        <active>1</active>
        </testimonial>
    <testimonial id="4c05085e1cd4f">
        <name>ats</name>
        <email>some@test.ee</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');
Run Code Online (Sandbox Code Playgroud)

版画

<?xml version="1.0"?>
<testimonials>
    <testimonial id="4c050652f0c3e">
        <nimi>John</nimi>
        <email>test@test.com</email>
        <text>Some text</text>
        <active>1</active>
        </testimonial>
    <testimonial id="4c05085e1cd4f">
        <name>LALALA</name>
        <email>some@test.ee</email>
        <text>Great site!</text>
        <active>0</active>
    </testimonial>
</testimonials>
Run Code Online (Sandbox Code Playgroud)