0

I'm trying to print complex XML's node values using XPath, I have attached an image for helping to see the path which I need to reach (red underline). XML image Original XML file can be found here

I was trying something like that:

<?php
$xml = simplexml_load_file('document.xml');

    echo "<strong>Using direct method...</strong><br />";
    $names = $xml->xpath('/w:document/w:body/w:tbl[0]/w:tr[1]/w:tc[0]/w:p/w:r/w:t');
    foreach($names as $name) {
        echo "Found $name<br />";
    }

?>

This method I am using to replace this node:

 $file = "document.xml";                                        
    $fp = fopen($file, "rb") or die("error");
    $str = fread($fp, filesize($file));
    $xml = new DOMDocument();                                
    $xml->formatOutput = true;
    $xml->preserveWhiteSpace = false;
    $xml->loadXML($str) or die("Error");

    $root   = $xml->documentElement;
    $fnode  = $root->childNodes->item(0);

    $ori    = $fnode->childNodes->item(1);                      
    $ori1    = $ori->childNodes->item(3);
    $ori2   = $ori1->childNodes->item(1);
    $ori3   = $ori2->childNodes->item(1);
    $ori4   = $ori3->childNodes->item(1);
    $ori5   = $ori4->childNodes->item(1);
        $wt     = $xml->createElement("w:t");
    $wtText = $xml->createTextNode("".$name." ".$item."");
    $wt->appendChild($wtText);
        $ori4->replaceChild($wt,$ori5);
        $xml->save("document.xml");
1
  • edited my post, I can reach that node using PHPDOM and replace that node, but I dont know how to read only this one xml node Commented May 15, 2012 at 17:39

1 Answer 1

1
<?php

// Load XML
$doc = new DOMDocument();
$doc->load("document.xml");

// Use xpath to grab the node in question. I copied your xpath
// query as-is, assuming it was capable of targetting exactly
// the node you are trying to replace. If it returns more than
// one node, then only the first will be replaced.
// If this isn't what you want, I suggest modifying your xpath
// query to match exactly the single node you want to replace.
$xpath = new DOMXPath($doc);
$oldElement = $xpath->query("/w:document/w:body/w:tbl[0]/w:tr[1]/w:tc[0]/w:p/w:r/w:t")->item(0);
$newElement = $doc->createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t", $name . " " . $item);

// Replace old element with new element
$oldElement->parentNode->replaceChild($newElement, $oldElement);

?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.