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

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");
    }
}
?>
1
  • 1
    What is the value of a testimonial? It has 4 children, what do you want to change? Commented Jun 2, 2010 at 10:05

1 Answer 1

17

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

prints

<?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>
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for XPath. I had the same idea but I didn't know which value should be changed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.