How do I print out ( the value at ) the index of a json object with the string "text" as the key value?

84 Views Asked by At
         // create curl resource
          $ch = curl_init();

          // set url 
          curl_setopt($ch, CURLOPT_URL, 

          "https://uselessfacts.jsph.pl/random.json?" . 

          "language=en");

          // $output contains the output json
          $output = curl_exec($ch);

          // close curl resource to free up system resources 
          curl_close($ch);


          $outputArray = json_decode($output, true);


          echo "<br><br><br><br>" . $outputArray[0]->text;

I get an error -

"Trying to retrieve a non-object."

I presume that the decoded object is a mixed object and not an array. Which makes it more complicated.

I'm simply trying to retrieve the string which belongs to the indice "text". There are 6 indices, I'm trying to retrieve the second one, and print it. I thought about using a foreach loop or a for loop, maybe I need a while loop with a single if statement. I think the easiest way is just to access the index directly and store it in a string.

Appreciate the help.

1

There are 1 best solutions below

1
webshifu On BEST ANSWER

See the below code. I have made some changes with comments explaining it.

// create curl resource
      $ch = curl_init();

      // set url 
      curl_setopt($ch, CURLOPT_URL, 

      "https://uselessfacts.jsph.pl/random.json?" . 

      "language=en");

      // set the return value to ture as it was returning bool for success
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

      // set the return response to json type
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));

      // $output contains the output json
      $output = curl_exec($ch);

      // close curl resource to free up system resources 
      curl_close($ch);


      $outputArray = json_decode($output, true);

      echo "<br><br><br><br>" . $outputArray['text'];