Extracting XML Response Using PHP cURL
When invoking PHP cURL method and receiving an XML response, it is often desirable to store it in a structured format for easy parsing. While cURL typically saves the response as a scalar type variable, there are ways to convert it into an object or associative array.
To achieve this, consider the following code snippet:
<code class="php">function download_page($path){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$path); curl_setopt($ch, CURLOPT_FAILONERROR,1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT, 15); $retValue = curl_exec($ch); curl_close($ch); return $retValue; } $sXML = download_page('http://alanstorm.com/atom'); $oXML = new SimpleXMLElement($sXML); foreach($oXML->entry as $oEntry){ echo $oEntry->title . "\n"; }</code>
In this code, the download_page function retrieves the XML response as a string. The SimpleXMLElement class is then used to convert the string into an object. This object can be easily iterated over and the desired data can be extracted.
For instance, in the code provided, the foreach loop iterates over each entry element in the XML response and prints out the title.
The above is the detailed content of How to Parse and Extract Data from an XML Response Using PHP cURL?. For more information, please follow other related articles on the PHP Chinese website!