Link to home
Start Free TrialLog in
Avatar of mr_stevie
mr_stevieFlag for Australia

asked on

Editting specific data in XML using PHP

Hello EE,

I am working on a small project that is making a small shopping website.

I am trying to implement the following code:

// Read the saved session variable
$myCart = $_SESSION["Cart"];

// Load the XML Document
$doc = new DomDocument('1.0');
$doc->load( "data.xml" );
$getItems = $doc->documentElement;

// Iterate through the array passed through containing the items.
foreach( $myCart as $Item )
{
	// Create a new XPath Variable.
	$xpath = new DOMXPath( $doc );

	// Get the correct element needed to be changed.
	$getSold = $xpath->query('/Items/Item[ItemID="' + $Item + '"]/Sold');
	$getHold = $xpath->query('/Items/Item[ItemID="' + $Item + '"]/Hold');

	// Change it to the new values.
	$getSold->item(0)->nodeValue += $getHold;
	$getHold = "0";
}

// Save the XML Document
$doc->save( $filename );
echo $doc->saveXML();

Open in new window


In this code, I am storing a session variable of "Item IDs" that will be copied into a variable and the code will iterate through all the elements in the array.

For each Item ID, I need to increment the corresponding "Sold" value by the "Hold" value and reset the value of "Hold" back to "0" in an XML document that is loaded.

At the end, the XML document needs to be saved.

The XML File looks like the following:

<?xml version="1.0" encoding="utf-8"?>
<Items>
	<Item>
		<ItemID>ABC001</ItemID>
		<Name>Book1</Name>
		<Price>4.99</Price>
		<Qty>5</Qty>
		<Hold>5</Hold>
		<Sold>0</Sold>
	</Item>
	<Item>
		<ItemID>ABC002</ItemID>
		<Name>Book2</Name>
		<Price>14.99</Price>
		<Qty>5</Qty>
		<Hold>5</Hold>
		<Sold>1</Sold>
	</Item>
	<Item>
		<ItemID>ABC003</ItemID>
		<Name>Book3</Name>
		<Price>24.99</Price>
		<Qty>5</Qty>
		<Hold>10</Hold>
		<Sold>2</Sold>
	</Item>
</Items>

Open in new window


Please note I'm quite new to working with XML and XPath and I hope this makes sense and someone can help me.

Thank you very much in advance.
ASKER CERTIFIED SOLUTION
Avatar of mr_stevie
mr_stevie
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mr_stevie

ASKER

Solution was developed by the original poster whilst waiting for an answer.