Hi every one. In previous post i had describe how to call the REST web services. Now a days we need to have our web services to be platform independent. To share the data between two different platforms, we will use the XML to communicate. Many web service send XML tagged data in response. So we need to parse that data in our page.
To do this we will use the built in PHP functions. Now Remember last post about PHP in this blog.
we have $response variable to store the response of web service. now suppose the response is in XML format as bellow.
//XML response format.
<?xml version="1.0" encoding="ISO-8859-1"?>
<temperature>
<date>27</date>
<month>04</month>
<year>2012</year>
<min>10</min>
<max>25.5</max>
<current>24</current>
</temperature>
It returns temperature of city that you pass as a parameter in web service in XML format.
Now if we want to parse this XML response we can add some code in previous post code.
<?php
//extracting data
$city=$_POST['city'];
//set URL
$url = "www.myservice.com";
//data
$data = "city=".$city;
//Initialize and Set option for cURL object
$pst = curl_init();$pst = curl_setopt($pst,CURLOPT_URL,$url);
$pst = curl_setopt($pst,CURLOPT_POST,true);
$pst = curl_setopt($pst,CURLOPT_RETURNTRANSFER,true);
$pst = curl_setopt($pst,CURLOPT_POSTFIELDS,$data);
//execute cURL objext
$result = curl_exec();
//close cURL object
curl_close($pst);
//Initialize the XML parser
$parser=xml_parser_create();
//Function to use at the start of an element
function start($parser,$element_name,$element_attrs){
switch($element_name)
{
case "temperature":
echo "<h1>Temperature is :</h1><br />";
break;
case "date":
echo "Date: ";
break;
case "month":
echo "Month: ";
break;
case "year":
echo "Year: ";
break;
case "min":
echo "<br/>Lowest: ";
break;
case "max":
echo "<br/>Maximum: ";
echo "<br/>Maximum: ";
break;
case "current":
echo "<br/>Current: ";
echo "<br/>Current: ";
break;
}
}
{
echo "/";
}
{
echo $data;
}
xml_parse($parser,$response);
}
}
//Function to use at the end of an element
function stop($parser,$element_name){
echo "/";
}
//Function to use when finding character data
function data1($parser,$data){
echo $data;
}
//Specify element handler
xml_set_element_handler($parser,"start","stop");
//Specify data handler
xml_set_character_data_handler($parser,"data1");xml_parse($parser,$response);
//Free the XML parser
xml_parser_free($parser);
?>
Steps.
To do this follow this steps.
1. Initialize XML parser variable with xml_parser_create() funtion.
2. Create function to handle start and end of XML tag.
3. Create function for handling data in XML tag.
4. Specify element handler functions using xml_set_element_handler() function.
5. Specify data handler function using xml_set_character_handler() function.
6. Specify the $parser variable with XML source.
7. Free $parser with xml_parse_free() function.
Change as per your requirements, and enjoy.
by. Nanji Parmar
No comments:
Post a Comment