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

我有這樣的XML晶格結構,我需要找到特定的標識和變化一個證明並保存文件。 我有一個PHP腳本根據其ID刪除特定的告別賽:更改XML節點元素值並保存文件

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

什麼是告別賽的價值?它有4個孩子,你想改變什麼? – 2010-06-02 10:05:40

回答

17

您可以使用XPath找到特定元素。 SimpleXMLElement->xpath()返回(匹配)SimpleXMLElement對象數組,即您可以訪問和更改每個元素的數據,就像在「您的」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'); 

打印

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

XPath的+1。我有同樣的想法,但我不知道應該改變哪個值。 – 2010-06-02 10:19:51