首页 > 解决方案 > 使用来自另一台服务器的 URL 解码 json 数据

问题描述

我从 MySQL 数据库中获取数据并将其编码为 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); 

 ?>

但是,当另一个脚本尝试对其进行解码时:

<?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']; 
?>

我得到一个错误。

标签: phpmysqli

解决方案


推荐阅读