Home >Backend Development >PHP Tutorial >How to Send HTTP GET Requests and Retrieve XML Data in PHP?

How to Send HTTP GET Requests and Retrieve XML Data in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-01 09:38:10546browse

How to Send HTTP GET Requests and Retrieve XML Data in PHP?

Sending GET Requests in PHP

Question: How can I send an HTTP GET request to retrieve XML content from a URL using PHP?

Answer:

To download XML content from a URL using a GET request in PHP, you have two main options:

1. Using file_get_contents()

If you simply need the contents of the XML file, you can use the file_get_contents() function. Here's how:

$xml = file_get_contents("http://www.example.com/file.xml");

2. Using cURL

For more complex requests, where you may need to handle cookies, headers, or other HTTP-specific features, consider using cURL. Here's an example:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/file.xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec($ch);
curl_close($ch);

The curl_exec() function returns the response body, which you can assign to the $xml variable.

The above is the detailed content of How to Send HTTP GET Requests and Retrieve XML Data in PHP?. 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