开发者

php and simpleXml - how to change node contents

I'm trying to change the contents of a node in an XML file using simpleXML. I know that the variable for the new node-contents contains the right stuff, but for some reason the file isn't changed when it is saved. I'm probably missing something basic, because I'm new to simpleXML. Here is the whole php script:

<?php 
    $doc=$_REQUEST["book"];
    $div1=$_REQUEST["div1"];
    $div2=$_REQUEST["div2"];
    i开发者_JAVA百科f ($div1=="") $div1=$_REQUEST["chapter"];
    if ($div2=="") $div2=$_REQUEST["verse"];
    $div3=$_REQUEST["div3"];
    $textresponse=$_REQUEST["xmltext"];
    $strippedresponse = "<?xml version='1.0'?>" . stripslashes($textresponse);
    echo("Saved changes to " . $doc . " " . $div1 . "." . $div2 ."<br />");    
    $fileName="/home/ocp/public_html/sites/default/docs/drafts/".$doc.".xml";
    $xmlDoc = simplexml_load_file($fileName);
    $backupFileName="/home/ocp/public_html/sites/default/docs/backups/".$doc." ".date("Y-m-d H.i.s").".xml";
    file_put_contents($backupFileName, $xmlDoc->asXML());
    $backupSize = filesize($backupFileName);
    echo("Backup {$backupFileName} created:".$backupSize." bytes<br />");
    if ($doc) {
        if ($div1) {
            if ($div2) {
                $newVerse = simplexml_load_string($strippedresponse);
        $oldVerse = $xmlDoc->xpath("//div[@number='".$div1."']/div[@number='".$div2."']"); 
        $oldVerse = $newVerse;

                $newDoc = $xmlDoc->asXml();
            file_put_contents($fileName, $newDoc);
            $newSize = filesize($fileName);
                echo("New file is ".$newSize." bytes <br />");
            }
        }
    }
?>


I'll venture to say that this code certainly doesn't do what you want it to:

$newVerse = simplexml_load_string($strippedresponse);
$oldVerse = $xmlDoc->xpath("//div[@number='".$div1."']/div[@number='".$div2."']"); 
$oldVerse = $newVerse;

Changing the value of a PHP variable has no side-effects. In other word, nothing happens when you do $a = $b; except in some specific cases, and it's not one of them.

I don't know what you really want to achieve with this code. If you want to replace the (X)HTML inside a specific <div/> you will need to use DOM and create a DOMDocumentFragment, use appendXML() to populate it then substitute it to your old <div/>. Either that or create a new DOMDocument, loadXML() then importNode() to your old document and replaceChild() your old div.


SimpleXMLElement::xpath returns an array of SimpleXMLElement objects. Copies, not references. So $oldVerse = $newVerse; does not change $xmlDoc in any way. SimpleXML is sufficient to read XML, for manipulation you might want to choose a more powerful alternative from http://www.php.net/manual/de/refs.xml.php, e.g. DOM.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜