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

Tôi có strcuture XML này và tôi cần phải tìm một lời chứng thực với id cụ thể và thay đổigiá trị của nó và lưu tập tin. Tôi có một kịch bản PHP xóa lời chứng thực cụ thể theo ID của nó:Thay đổi nút XML giá trị phần tử trong PHP và lưu tập tin

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

giá trị của một lời chứng thực là gì? Nó có 4 đứa con, bạn muốn thay đổi cái gì? –

Trả lời

17

Bạn có thể sử dụng XPath để tìm các yếu tố cụ thể. SimpleXMLElement->xpath() trả về một mảng các đối tượng SimpleXMLElement (phù hợp), tức là bạn có thể truy cập và thay đổi dữ liệu của mỗi phần tử giống như bạn sẽ làm trong vòng lặp foreach của bạn.

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

in

<?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 cho XPath. Tôi đã có ý tưởng tương tự nhưng tôi không biết giá trị nào nên được thay đổi. –

Các vấn đề liên quan