Home > Backend Development > PHP Tutorial > How to Parse and Extract Data from an XML Response Using PHP cURL?

How to Parse and Extract Data from an XML Response Using PHP cURL?

Barbara Streisand
Release: 2024-10-26 21:15:29
Original
398 people have browsed it

How to Parse and Extract Data from an XML Response Using PHP cURL?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template