Reputation: 3
I'm trying to return JSON results from a page but I get the following error using file_get_contents(): " failed to open stream: HTTP request failed! "
Can someone tell me why I get this error?
<?
$newURL = 'https://api.qwant.com/api/search/images?count=10&offset=1&q=Spicy
Cranberry Cavolo Nero (Kale)';
$returnedData = file_get_contents($newURL);
?>
Upvotes: 0
Views: 2411
Reputation: 46
<? ?>
. Use only <?php ?>
or <?= ?>
file_get_contents() is not a really good method to receive data from the outer servers. Better use CURL.
<?php
// Your URL with encoded parts
$newURL = 'https://api.qwant.com/api/search/images?count=10&offset=1&q='.urlencode('Spicy Cranberry Cavolo Nero (Kale)');
// This is related to the specifics of this api server,
// it requires you to provide useragent header
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => 'any-user-agent-you-want',
);
// Preparing CURL
$curl_handle = curl_init($newURL);
// Setting array of options
curl_setopt_array( $curl_handle, $options );
// Getting the content
$content = curl_exec($curl_handle);
// Closing conenction
curl_close($curl_handle);
// From this point you have $content with your JSON data received from API server
?>
Upvotes: 1