John test@test.com So...">

Change XML node value in PHP and save file

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

I have XML strcuture and I need to find a review with a specific identifier and change its value and save the file. I have a PHP script that removes a specific review by 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"); } } ?> 
+6
dom xml php
source share
1 answer

You can use XPath to find a specific item. SimpleXMLElement-> xpath () returns an array of (compatible) SimpleXMLElement objects, that is, you can receive and modify the data of each element in the same way as you do 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'); 

prints

 <?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> 
+17
source share

All Articles