0

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);

?>
4
  • Any reason not to have "api.qwant.com/api/search/…" instead of what you have right now? With %20 for each space Commented Jan 5, 2018 at 22:07
  • Possible duplicate of PHP file_get_contents() returns "failed to open stream: HTTP request failed!" Commented Jan 5, 2018 at 22:09
  • have your tried to escape the parameters correctly? for example, replace the spaces with %20 in the url. Commented Jan 5, 2018 at 22:24
  • @RAZERZ I tried doing a urlencode on the query itself but it gives me a different error (Too many request): $baseURL = 'api.qwant.com/api/search/images?'; $query = urlencode("count=10&offset=1&q=Spicy Cranberry Cavolo Nero (Kale)"); $composedURL = $baseURL.$query; $returnedData = file_get_contents($composedURL); Commented Jan 5, 2018 at 22:39

1 Answer 1

1
  1. Never use <? ?>. Use only <?php ?> or <?= ?>
  2. urlencode() use only on values of your parameters, not on the whole parameter's line.
  3. 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
    
    ?>
    
Sign up to request clarification or add additional context in comments.

1 Comment

and you can send POST requests with curl as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.