Get value from XML and do calculation in PHP

Description

The following code shows how to get value from XML and do calculation.

Example


/* w w  w. java 2 s .  co m*/
<?php
$xml = simplexml_load_file('test.xml');
foreach ($xml->book as $book) {
  // Remove the dollar sign
  $reduced = substr($book->price->paperback, 1);
  // Multiply by .9 to give 10% discount
  $reduced *= .9;
  // Format the number, and reassign it to the original property
  $book->price->paperback = '$' . number_format($reduced, 2);
}
header ('Content-Type: text/xml');
echo $xml->asXML();
?>

The following code is for test.xml.


/*from   w w  w  .j  a va  2s  . c o  m*/
<?xml version='1.0' encoding='utf-8'?>
<inventory>
  <book isbn13='1'>
    <title>PHP</title>
  <author>Jack</author>
  <publisher>friends of ED</publisher>
  <description>PHP Book</description>
  <price>
    <paperback>$3.99</paperback>
    <ebook>$2.89</ebook>
  </price>
  </book>
  <book isbn13='8'>
    <title>XML</title>
  <author>Jane</author>
  <publisher>Apress</publisher>
  <description>XML Book</description>
  <price>
    <paperback>$4.99</paperback>
    <ebook>$3.99</ebook>
  </price>
  </book>
</inventory>

The code above generates the following result.





















Home »
  PHP Tutorial »
    XML »




DOM
SimpleXML
SimpleXMLElement
XML Parser