遇到具有图片网址的json的人

时间:2018-08-17 17:57:37

标签: php json

我试图制作json文件以将我的数据从数据库转换为json并最终出现错误(SyntaxError:JSON.parse:JSON数据第1行第1列的意外字符)

当我使用不包含img_url的数据库时,它可以工作,但是当存在img_url时始终出错。 我尝试使用.php扩展名,它可以工作,但是img_url混乱,但是当我使用.json扩展名时,显示错误

这是我的代码:

$stmt = $conn->prepare("SELECT namajurusan, fakultas, deskripsi, img_url FROM tbl_prodi;");

//executing the query 
$stmt->execute();

//binding results to the query 
$stmt->bind_result($namajurusan, $fakultas, $deskripsi, $img_url);

$prodi = array(); 

//traversing through all the result 
while($stmt->fetch()){
    $temp = array();
    $temp['namajurusan'] = $namajurusan; 
    $temp['fakultas'] = $fakultas; 
    $temp['deskripsi'] = $deskripsi; 
    $temp['img_url'] = $img_url;  
    array_push($prodi, $temp);
}

//displaying the result in json format 
echo json_encode($prodi);

2 个答案:

答案 0 :(得分:0)

在将网址添加到json之前,先使用urlencode对网址进行编码。

PHP文档:http://php.net/manual/en/function.urlencode.php

更新:

使用array_push($prodi, $temp);代替使用$prodi[] = $temp

答案 1 :(得分:0)

在调用json_encode之前,请确保没有将未解析的字符串发送到JSON。 尝试使用var_dump()来查看它。