Я пытался создать метод добавления новых элементов в XML-файл, но по какой-то причине он не изменяет элемент, даже если при использовании saveXML
выводятся правильные.
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);
}
}
Этот код принимает идентификатор и в зависимости от идентификатора изменяет информацию на четырех элементах.
Вот XML-файл
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/>
У вас есть идеи, почему это может не сработать?