[英]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.