1

I fetch data from a MySQL database and encode it to JSON:

<?php 
   error_reporting(0);
   //Connection information to the Server
   $servername = "localhost";
   $username = "root";
   $password = "";
   $dbname = "wordpress";
   $conn = new mysqli($servername, $username, $password, $dbname);
   mysqli_select_db($dbname);

   $sql = "SELECT * FROM `wp_posts` ";
   $query = $conn->query($sql);
   $dataArray=array();
   while($row=mysqli_fetch_array($query)){
       $temp['post_title'] = $row['post_title'];
       $temp['post_date'] = $row['post_date'];
       array_push($dataArray, $temp); 
   }
   echo json_encode(array("wp_posts"=>$dataArray),JSON_UNESCAPED_UNICODE); 

 ?>

However, when another script tries to decode it:

<?php 
    error_reporting(0);
    $get_data = file_get_contents("http://localhost:6060/php/api-test/api.php");
    $json = json_decode($get_data, true);
    $response = json_decode($get_data, true); //because of true, it's in an array
    echo 'Online: '. $response['post_title']; 
?>

I get an error.

James
  • 20,957
  • 5
  • 26
  • 41
Mohamed Atef
  • 23
  • 1
  • 3
  • 1
    How are you determining that it failed? Have you tried some debugging? Check [`json_last_error_msg()`](http://php.net/manual/function.json-last-error-msg.php). If both your PHP scripts are running on the same server, you don't need to use `file_get_contents()`, see [require/include into variable](https://stackoverflow.com/questions/5948395/require-include-into-variable) – Phil Nov 08 '18 at 22:56
  • Ah sorry, you said they were on different servers. Ignore that last point – Phil Nov 09 '18 at 02:29
  • 1
    Show the error message. Also decode the `json` immediately after encoding in the first script and see what happens. These first steps would help you and others to find what is the problem and where it it is being generated.. – bcperth Nov 09 '18 at 02:50
  • there is no error message but there is no data in the page (empty page) – Mohamed Atef Nov 09 '18 at 12:27

0 Answers0