使用php替换xml的部分

I'm trying to post some data via ajax to a php file which writes some xml. I basically want to post bits of data and replace a certain part of the xml.

The js:

$(".aSave").click(function(){
    var name = $(this).attr("data-name");
    var value = $(this).attr("data-value");
    var dataObj = {};
    dataObj[name]=value;

    $.ajax({
        url: 'view/template/common/panel.php',
        type: 'post',
        data: dataObj,
    }).done(function(){
        alert("saved!");
    });
});

The php:

<?php
    $fruits [] = array(
        $orangesValue = $_POST['oranges'],
        $applesValue = $_POST['apples'], 
    ); 

    $doc = new DOMDocument(); 
    $doc->formatOutput = true; 

    $mainTag = $doc->createElement( "fruits" ); 
    $doc->appendChild( $mainTag ); 

    $oranges = $doc->createElement("oranges"); 
    $oranges->appendChild($doc->createTextNode($orangesValue)); 
    $mainTag->appendChild($oranges);

    $apples = $doc->createElement("apples"); 
    $apples->appendChild($doc->createTextNode($applesValue)); 
    $mainTag->appendChild($apples);

    echo $doc->saveXML(); 
    $doc->save("fruits.xml")
?>

So now when I send the oranges value it writes a new xml file containing the oranges value only. Is it possible to replace only the value which i'm posting.

Cheers

So if I understand you correctly, you want to read an existing XML-Document, replace the text content of the oranges element and save the document again?

Try this then:

$fileName = '/my/absolute/path/to/my/file.xml';
$doc = new DOMDocument();
$doc->load($fileName);
$nodes = $doc->getElementsByTagName('oranges');

if (NULL != $nodes) {
  $nodes->item(0)->nodeValue = $_POST['oranges'];
}

$doc->save($fileName);

But this is overly complicated (or me hating the DOM extension). If you have the simplexml extension available, try this:

$fileName = 'blabla.xml';
$xml = simplexml_load_file($fileName);
$xml->oranges = $_POST['oranges'];
$xml->asXML($fileName);

Of course you'd need to check your $_POST data for correctness before writing it in your XML file. If you want to act based on whether you posted apples or oranges, replace oranges with a variable:

foreach ($_POST as $fruit => $val) {
  $xml->{$fruit} = $val;
}