在PHP中更改XML节点元素值并保存文件 [英] Change XML node element value in PHP and save file

查看:107
本文介绍了在PHP中更改XML节点元素值并保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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>

我有这个XML strcuture,我需要找到一个具体的id和 / strong>其并保存文件。
我有一个PHP脚本根据其ID删除特定的证明:

I have this XML strcuture and i need to find a testimonial with specific id and change its value and save file. I have a PHP script deleting specific testimonial according its 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");
    }
}
?>


推荐答案

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

You can use XPath to find the specific element. SimpleXMLElement->xpath() returns an array of (matching) SimpleXMLElement objects, i.e. you can access and change the data of each element just like you would in "your" foreach loop.

<?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');

打印

<?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>

这篇关于在PHP中更改XML节点元素值并保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆