我有一些问题,我创建了php文件(json_code.php)并编写了php代码来创建JSON输出。代码如下:
require_once('connect.php');
require_once('studentdb.php');
$query = $conn->prepare("SELECT * FROM student");
$query->execute();
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$temp_student = new StudentDB($data['id'], $data['name'], $data['address'], $data['age']);
$student_array[] = $temp_student;
}
header("Content-Type: application/json");
$dale_data = json_encode($student_array[0]);
echo '{"student":[';
echo $dale_data;
echo ']}';
JSON输出显示如下:
{"student":[{"id":"1","name":"Ghale","address":"Street abcdfgh","age":"22"}]}
我想用另一个文件php读取JSON,然后我创建文件read_json.php,代码如下:
$json_url = 'http://localhost/test1/json_code.php';
$ch = curl_init( $json_url );
$json_string = array();
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
curl_setopt_array( $ch, $options ); // Setting curl options
echo $result = curl_exec($ch); // Getting jSON result string
$decode = json_decode($result, true);
print_r($decode);
但它没有显示任何东西:( 如何读取另一个文件php的JSON输出?请帮忙:(抱歉英语不好
答案 0 :(得分:0)
如果你使用file_get_contents来获取你的JSON,我认为它会更容易,更容易混淆。试试这个:
echo json_decode(file_get_contents('http://localhost:82/test1/json_code.php'));
如果您只想检查json_code.php文件的输出,请执行以下操作:
echo file_get_contents('http://localhost:82/test1/json_code.php');