I'm using multiple API's, all of which get called using cURL. Someone on Reddit recommended code that looks like this:
function fetch($url, $the_id = null)
{
// Initiate the cURL fetch
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Send authorization header with the the ID. Without this, the query won't work
if ($the_id) curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$the_id));
$result = curl_exec($ch);
curl_close($ch);
// Put the results to an object
return simplexml_load_string($result) or die("Error: Cannot create object");
}
// Without auth id
$test = fetch('http://forums.phpfreaks.com');
// With auth id
$test = fetch('http://forums.phpfreaks.com', 't_v');
But when I then use the foreach to pull the data from the API, it produces no results.
foreach($result->things->children() as $thing) {
echo "<p>". $thing->cool_thing ."</p>";
echo "<p>". $thing->cooler_thing ."</p>";
}
Whether I use echo fetch(parameters); or fetch(); it does get any results, unlike if I used it outside of a function.