I have been trying to make a method for adding new elements in an XML file, but for some reason it does not modify the element, even that when i Use saveXML prints the right ones.
function fnDOMEditElementCond($product_id, $name, $weight, $category, $location) {
if (!isset($product_id) || is_numeric($product_id)) {
return false;
}
$obj = new helperClass();
$xmlDoc = $obj->fetchFromXMLDocument('storage.xml');
$xpath = new DOMXPath($xmlDoc);
$result = $xpath->query(sprintf('/storagehouse/item[@id="%s"]', $product_id));
if (!$result || $result->length !== 1) {
throw new Exception(sprintf('Item with id "%s" does not exists or is not unique.', $product_id));
}
$item = $result->item(0);
//Change the name element
$xName = $xpath->query("./name", $item)->item(0);
$xName->removeChild($xName);
// //Change the name element
// $xWeight = $xpath->query("./weight", $item)->item(0);
// $xWeight->nodeValue = $weight;
//
// //Change the name element
// $xLocation = $xpath->query("./location", $item)->item(0);
// $xLocation->nodeValue = $category;
//
// //Change the name element
// $xCategory = $xpath->query("./category", $item)->item(0);
// $xCategory->nodeValue = $location;
echo $xmlDoc->saveXML($item);
}
}
This code takes a ID, and depending on the id it modifies the information, on four elements.
Here is the xml fil
storagehouse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="schema.xsd">
<item id="c7278e33ef0f4aff88da10dfeeaaae7a">
<name>HDMI Cable 3m</name>
<weight>0.5</weight>
<category>Cables</category>
<location>B3</location>
</item>
<item id="df799fb47bc1e13f3e1c8b04ebd16a96">
<name>Dell U2410</name>
<weight>2.5</weight>
<category>Monitors</category>
<location>C2</location>
</item>
<item id="53abbd89766ea8759b5ebe5bacd43f58">
<name>HP Probook 1311</name>
<weight>2.1</weight>
<category>Notebooks</category>
<location>A1</location>
</item>
<storagehouse/>
Do you have any idea on why that it might not working?
I believe it is because you are looking for save() not savexml(). And you will need to give save() the filename.
Edit: Also, if I’m remembering correctly, you will need to reload the DOM after each save, otherwise you will only effect the unsaved DOM elements. But it’s been a while since I’ve had to do it. I’ll take a look through my old code to double check.
Edit Again: I’ve been looking through my code, and it does appear to be necessary. You can do all the modifications you need at once, but if you need to view the results in the interim, you either have to produce it with saveXML() or save() it and read it into a fresh XML object. The original object will only reflect the original content. I didn’t properly note it in my comments like I should have, but my code is done in such a way that it makes me think I am right. Hopefully this helps.