Retrieving XML With Curl and SimpleXMLIntroductionPHP 5 introduces SimpleXML and its a perfect name as parsing XML data is truly simple. In this tutorial we'll be using curl to retrieve the XML data from a remote web server. We're going to create a class to connect to the remote web server and pass POST data to the server and based on the POST data the remote server will return valid XML. The class will parse the XML response and return an array containing the data. For the sake of simplicity in this tutorial we're not going into detail on the workings of the remote server generating the XML responses.
The first thing we're going to cover is the simple script used to call the class.
<?
$URL = ‘http://www.example.com/XML’;
$request = ‘getInventory’;
$parameters = array(“param1” => “value1”, “param2” => “value2″);
$XMLClass = new getXML;
$response = $XMLClass->pullXML($URL,$request,$parameters);
?>
This simple script is all that is needed to use the class. We need to set the URL, request, and attributes being passed for the request. The $XMLClass = new getXML initializes the getXML class discussed later on in the tutorial. The response data of the request is stored in $response. For this example we’re going to use the following XML.
<?
<xml>
<data>
<row attribA=”valueA” attribB=”valueB”/>
<row attribA=”valueC” attribB=”valueD”/>
</data>
</xml>
?>
var_dump($response) would be
array2 { [0]=> array2 { [“attribA”]=> string6 “valueA” [“attribB”]=> string6 “valueB” } [1]=> array2 { [“attribA”]=> string6 “valueC” [“attribB”]=> string6 “valueD” } }