How to Extract and Parse XML Responses with PHP cURL?

DDD
Release: 2024-10-27 06:43:29
Original
515 people have browsed it

How to Extract and Parse XML Responses with PHP cURL?

Extracting XML Responses with PHP cURL

When using PHP's cURL method to retrieve responses from servers, you may encounter situations where the response is in XML format. However, by default, cURL stores the output in a scalar type variable, making it challenging to parse efficiently.

To address this issue, here's a method to convert the XML response into an object, hash, or array for easier parsing:

<code class="php"><?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 example, we:

  1. Use the download_page() function to retrieve the XML response as a string ($sXML).
  2. Create a SimpleXMLElement object ($oXML) from the XML string.
  3. Loop through the XML elements and access their properties, such as title.

The above is the detailed content of How to Extract and Parse XML Responses with 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!