Last active
August 28, 2023 15:49
-
-
Save keithgreer/88b5ff3f9c3da1b02cd2424081c6c221 to your computer and use it in GitHub Desktop.
PHP cURL Requests with JSON or XML - https://keithgreer.dev/php-curl-requests-json-xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Initilise cURL | |
$ch = curl_init(); | |
// Set the cURL Options | |
$optArray = array( | |
CURLOPT_URL => 'https://example.com/api/getInfo/', | |
CURLOPT_RETURNTRANSFER => true | |
); | |
// Set the Headers | |
$headers = [ | |
"Access-Key: 123456789QWERTYUIOP", | |
"Access-Token: ASDFGHJKL0987654321", | |
]; | |
// Add Options and Headers | |
curl_setopt_array($ch, $optArray); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); | |
// Submit Request | |
$result = curl_exec($ch); | |
// Convert JSON to Object | |
$processed = json_decode($result, true); | |
// OR Convert from XML to object | |
// $processed = simplexml_load_string($result); | |
curl_close($ch); | |
// Check that $processed has a value | |
if ($processed === false) { | |
echo "Failed loading resource: "; | |
} else { | |
// Dump the object | |
echo "<pre>"; | |
print_r$processed); | |
echo "</pre>"; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment