繁体   English   中英

从另一个文件php解码json

[英]decode json from another file php

我有一些问题,我创建了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输出?请帮助:(对不起,英语不好

我认为,如果您使用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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM