Skip to content

Instantly share code, notes, and snippets.

@keithgreer
Last active August 28, 2023 15:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save keithgreer/88b5ff3f9c3da1b02cd2424081c6c221 to your computer and use it in GitHub Desktop.
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
<?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