Search code examples
phphttp-headers

Reading simple API returns blank screen?


For some reason I cannot figure out how to fix this online anywhere? I have this simple free Chuck Norris joke API that I'm simply trying to output the JSON of, but it wont work? I just get a blank screen?

In the console the network tab says 200 ok and that the headers are valid? What am I doing wrong?

My code:

<?php

  
  header('Content-Type: application/json');
  header('X-RapidAPI-Host: matchilling-chuck-norris-jokes-v1.p.rapidapi.com');
  header('X-RapidAPI-Key: 341b5c1156msh6827bf7184ef4ddp1c8d09jsnbc52db5d01be');
 


  $str = file_get_contents('https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random');
  
// decode JSON
$json = json_decode($str, true);

// get the data

print_r($json);

Solution

  • Most likely you want to send those headers...

    header prints out the headers to you, locally, where you execute it.

    With file_get_contents it will be like this:

    <?php
    $opts = [
        "http" => [
            "method" => "GET",
            "header" => "Content-Type: application/json\r\n" .
                "X-RapidAPI-Host: matchilling-chuck-norris-jokes-v1.p.rapidapi.com\r\n" .
                "X-RapidAPI-Key: 341b5c1156msh6827bf7184ef4ddp1c8d09jsnbc52db5d01be\r\n"
        ]
    ];
    
    $context = stream_context_create($opts);
    $str = file_get_contents('https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random', false, $context);
    
    // decode JSON
    $json = json_decode($str, true);
    
    // get the data
    print_r($json);
    

    I also kindly suggest switching to curl extension.