Sunday, January 25, 2009

Parsing string into XMLReader in PHP5

Problem: How to parse string result into XML parser in PHP5
Solution: Use one of several PHP5 extensions such as XMLReader

$reader = new XMLReader();
$reader->XML($resultInString);

Below is the sample code that calls PTT Web Services and extracting only the price of GASOHOL

<?php

$wsdl = 'http://www.pttplc.com/pttinfo.asmx?WSDL';

$client = new SoapClient($wsdl);
//array('proxy_host' => "202.12.97.116",
//'proxy_port' => 8088));


$methodName = 'CurrentOilPrice';

$params = array('Language'=>'EN');

$soapAction = 'http://www.pttplc.com/ptt_webservice/CurrentOilPrice';

$objectResult = $client->__soapCall($methodName,
array('parameters' => $params), array('soapaction' => $soapAction));


// echo $objectResult->CurrentOilPriceResult;
$result = $objectResult->CurrentOilPriceResult;
$reader = new XMLReader();
$reader->XML($result);
$found = false;
while ($reader->read()) {
$tagName = $reader->name;
$reader->read();
$tagValue = $reader->value;
if ($tagName == "PRODUCT" &&
$tagValue == "GASOHOL") {
$found = true;
}
if ($found == true && $tagName == "PRICE") {
$price = $reader->value;
break;
}
}
echo "GASOHOL price is $price";
$reader->close();
?>


Then, you should get the result as shown in the below picture.





No comments: