2010-06-02 14 views
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> 

ho questo strcuture XML e ho bisogno di trovare una testimonianza con specifico ID e cambiamento sua valore e salvare il file. Ho uno script PHP eliminazione testimonianza specifica secondo il suo ID:Modifica nodo XML valore dell'elemento in PHP e salvare il file

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

Qual è il valore di una testimonianza? Ha 4 figli, cosa vuoi cambiare? –

risposta

17

È possibile utilizzare XPath per trovare l'elemento specifico. SimpleXMLElement->xpath() restituisce una matrice di oggetti SimpleXMLElement (corrispondenti), ad esempio è possibile accedere e modificare i dati di ciascun elemento proprio come si farebbe nel ciclo "proprio" di foreach.

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

stampe

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

+1 per XPath. Ho avuto la stessa idea ma non sapevo quale valore dovrebbe essere cambiato. –

Problemi correlati