Click here to Skip to main content
15,891,938 members
Articles / Programming Languages / PHP

Working with XML in PHP

Rate me:
Please Sign up or sign in to vote.
4.92/5 (15 votes)
3 May 2013CPOL3 min read 73K   2.1K   17  
Working with XML in PHP.
<?php
	//XMLwriter to write XML from scratch - Little complex example
	$xml = new XMLWriter();
	$xml->openMemory();
	$xml->startDocument();
		$xml->startElement("purchase");
			$xml->startElement("customer");							//Start of customer with id 1
				$xml->writeElement("id", 1);
				$xml->writeElement("time", "2013-04-19 10:56:03");
				$xml->writeElement("total", "$350");
			$xml->endElement();										//End of customer with id 1
			$xml->startElement("customer");							//Start of customer with id 2
				$xml->writeElement("id", 2);
				$xml->writeElement("time", "2013-04-23 13:43:41");
				$xml->writeElement("total", "$1456");
			$xml->endElement();										//End of customer with id 2
		$xml->endElement();
	$nXML =  $xml->outputMemory();							//Store the XML in $nXML
	
	/* 	XMLReader starts from here for Little Complex Example - XMLReader
		To get the total amount spent by custormer with id 1
	*/
	$rxml = new XMLReader();								//Create new XMLReader Object
	$rxml->xml($nXML);										//Load in the XML
	while($rxml->read() && $rxml->name !== 'customer');		//Move to the first customer child 
	
	$amountSpent = 0;
	while($rxml->name === 'customer')
	{														/* The child xml gotten using the readOuterXML() will look thus
																<customer><id>1</id><time>2013-04-19 10:56:03</time><total>$350</total></customer>
															*/
		$node = new SimpleXMLElement($rxml->readOuterXML());//Read the current child xml into a SimpleXMLElement
		if($node->id == 1)									//Check if the id node as 1 as it value
		{
			$amountSpent = $node->total;
			break;
		}
		$rxml->next('customer');							//Move to the next customer child
	}
	
	echo $amountSpent;
?>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Nigeria Nigeria
A graduate of Agricultural Engineering from Ladoke Akintola University of Technology, Ogbomoso but computer and web programming is his first love. You can meet him on Facebook Osofem Inc.

Comments and Discussions