View Category
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
php
$xmlfile = simplexml_load_file('shop.xml');
$x = 0;
foreach ($xmlfile as $xml) {
// we have to declare that it's a float
$x = $x + ($xml['quantity'] * (float)$xml['price']);
}
echo $x;
$filename = "shop.xml";
if (($fp = fopen($filename, "r"))) {
while ($data = fread($fp, 4096)) {
$data = eregi_replace(">"."[[:space:]]+"."< ",">< ", $data);
if (!xml_parse($xmlparser, $data, feof($fp))) {
$reason = xml_error_string(xml_get_error_code($xmlparser));
$reason .= xml_get_current_line_number($xmlparser);
die($reason);
}
}
xml_parser_free($xmlparser);
echo $total; // Echo the total
}

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
php
$xmllines = split("\n", $cvs);
foreach ($xmllines as $l) {
$xml[] = split(",", $l);
}
echo "<shopping>\n";
foreach ($xml as $x) {
echo "\t<item name=\"".$x[0]."\" quantity=\"".$x[1]."\" price=\"".$x[2]."\" />\n";
}
echo "</shopping>\n";