2010-06-02 21 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> 

que tienen esta strcuture XML y necesito encontrar un testimonio con id específico y cambio su valor y guardar el archivo. Tengo un script PHP borrar testimonio específica según su ID:Cambiar valor de elemento de nodo XML en PHP y guardar el archivo

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

¿Cuál es el valor de un testimonio? Tiene 4 hijos, ¿qué quieres cambiar? –

Respuesta

17

Puede utilizar XPath para encontrar el elemento específico. SimpleXMLElement->xpath() devuelve una matriz de objetos (coincidentes) SimpleXMLElement, es decir, puede acceder y cambiar los datos de cada elemento tal como lo haría en "su" ciclo 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'); 

impresiones

<?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 para XPath. Tenía la misma idea, pero no sabía qué valor debería cambiarse. –

Cuestiones relacionadas