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

बचाने मैं इस एक्सएमएल strcuture है और मैं विशिष्ट आईडी और परिवर्तन अपने मूल्य साथ एक प्रशंसापत्र खोजने के लिए और फ़ाइल को सहेजना होगा। मैं एक PHP स्क्रिप्ट अपने आईडी अनुसार विशिष्ट प्रशंसापत्र को हटाने है:बदलें एक्सएमएल नोड तत्व मूल्य और फ़ाइल

<?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 बच्चे हैं, आप क्या बदलना चाहते हैं? XPath के लिए –

उत्तर

17

आप XPath उपयोग कर सकते हैं विशिष्ट तत्व खोजने के लिए। SimpleXMLElement->xpath() SimpleXMLElement ऑब्जेक्ट्स (मिलान) की एक सरणी देता है, यानी आप प्रत्येक तत्व के डेटा को एक्सेस और बदल सकते हैं जैसे कि आप "your" foreach loop में करेंगे।

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

+1। मेरे पास एक ही विचार था लेकिन मुझे नहीं पता था कि कौन सा मूल्य बदला जाना चाहिए। –

संबंधित मुद्दे