在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..

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

It looks like you're populating $data with the text of db2.php instead of the output from running the file in php. Try this:

$data = `php db2.php`