|
<?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.