dsdzvprlp51692469 2014-04-15 02:30
浏览 46
已采纳

在PHP中,我从mySQL编写了一个JSON数组。 我想在不同的PHP文件中解码它

In Php, I encoded a JSON array from MySQL table . i want to decode it in different Php file . and i want to access the data through JavaScript from different file. anyone please help me.

MY code is:

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

Output is :

 {"tdata":[{"id":"1","name":"aaa"},{"id":"2","name":"bbb"},{"id":"3","name":"ccc"}]}

My decode Function is:

$data = file_get_contents('db2.php');

$data1 = json_decode($data, true);

print($data1);

but its not working..

  • 写回答

2条回答 默认 最新

  • dongzaheng4449 2014-04-15 02:49
    关注

    When you return JSON encoded string it is best if you send a proper headers. You should return JSON like that (you can still use print function):

    <?php
    header('Content-Type: application/json');
    echo json_encode($data);
    

    Now, when you retrieve this output, send it to json_decode function that will return an object.

    json_decode.

    file_get_contents function retrieves content of the file, it does not parse it. To retrieve the content of the file:

    • by calling it with an URL (DO NOT USE THIS ONE I am showing this method for the purpose of learning only, this function wont load URL if allow_url_fopen directive is off, instead you can use curl library (here))

      $json = file_get_contents('www.example.com/db2.php');
      echo json_decode($json, true);
      
    • by including it with a relative path

      $json = (include "db2.php");
      echo json_decode($json, true);
      

      in this particular scenario, db2.php has to use return statement like so

      return json_encode($response);
      
    • by using ob_* with include, this time you do not need to return in db2.php file

      ob_start();
      include "db2.php";
      $json = ob_get_contents();
      ob_end_clean();
      echo json_decode($json, true);
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器