Измените значение элемента XML-узла в PHP и сохраните файл - PullRequest
6 голосов
/ 02 июня 2010
<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, и мне нужно найти отзыв с конкретным идентификатором и изменить его значение и сохранить файл. У меня есть скрипт PHP, удаляющий конкретный отзыв в соответствии с его идентификатором:

<?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");
    }
}
?>

1 Ответ

17 голосов
/ 02 июня 2010

Вы можете использовать XPath , чтобы найти определенный элемент. SimpleXMLElement-> xpath () возвращает массив (соответствующих) объектов SimpleXMLElement, т. Е. Вы можете получать доступ к данным каждого элемента и изменять их так же, как в «вашем» цикле 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');

печать

<?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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...