简体   繁体   中英

decode json from another file php

I have some promblem, I create php file (json_code.php) and wrote php code to create JSON output. Here the code :

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

That JSON output showed like this:

{"student":[{"id":"1","name":"Ghale","address":"Street abcdfgh","age":"22"}]}

I want to read that JSON with another file php, then I create file read_json.php, the code like this :

$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);

But it's did not show anything :( How to read that JSON output from another file php? Please help :( Sorry for bad english

I think it will be easier and less confusing if you use file_get_contents to get your JSON. Try this:

echo json_decode(file_get_contents('http://localhost:82/test1/json_code.php'));

If you just want to examine the output of your json_code.php file do this:

echo file_get_contents('http://localhost:82/test1/json_code.php');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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