在 Php 中,我从 MySQL 表编码了一个 JSON 数组。我想在不同的 Php 文件中对其进行解码。我想通过 JavaScript 从不同的文件访问数据。有人请帮助我。
我的代码是:
$serverName = "(local)";
$connectionInfo = array( "Database"=>"sample");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.<br/>";
}
else
{
echo "Connection could not be established.<br/>";
die( print_r( sqlsrv_errors(), true));
}
$str="Select * from sam1";
$res=sqlsrv_query($conn,$str) or die("Error !");
$response=array();
while( $row = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC) )
{
$response['tdata'][]=$row;
}
print(json_encode($response));
输出是:
{"tdata":[{"id":"1","name":"aaa"},{"id":"2","name":"bbb"},{"id":"3","name":"ccc"}]}
我的解码函数是:
$data = file_get_contents('db2.php');
$data1 = json_decode($data, true);
print($data1);
但它不起作用..
最佳答案
当您返回 JSON
编码字符串时,最好发送正确的 header 。你应该像这样返回 JSON
(你仍然可以使用 print
函数):
<?php
header('Content-Type: application/json');
echo json_encode($data);
现在,当您检索此输出时,将其发送到将返回对象的 json_decode
函数。
file_get_contents
函数检索文件的内容,但不解析它。要检索文件的内容:
通过使用 URL 调用它(不要使用这个我展示此方法仅用于学习目的,如果
allow_url_fopen
指令是off
,则此函数不会加载 URL,而是您可以使用curl
库 ( here ))$json = file_get_contents('www.example.com/db2.php'); echo json_decode($json, true);
通过将其包含在相对路径中
$json = (include "db2.php"); echo json_decode($json, true);
在这个特定场景中,
db2.php
必须像这样使用return
语句return json_encode($response);
通过使用
ob_*
和include
,这次不需要return
文件中的db2.php
ob_start(); include "db2.php"; $json = ob_get_contents(); ob_end_clean(); echo json_decode($json, true);
关于javascript - 在 PHP 中,我从 mySQL 编码了一个 JSON 数组。我想在不同的 php 文件中解码它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23073672/