Home  >  Article  >  Backend Development  >  How to Extract and Parse XML Responses with PHP cURL?

How to Extract and Parse XML Responses with PHP cURL?

DDD
DDDOriginal
2024-10-27 06:43:29516browse

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>

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!

Statement:
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