json_encode没有得到回应

时间:2015-05-03 21:43:46

标签: php .net sql-server

我正在尝试使用下面的代码从数据库中提取一些记录,但代码末尾的echo json_encode($contacts);不会打印任何内容。任何echo都没有放在那之上。

<?php
    require_once(dirname(__FILE__).'/ConnectionInfo.php');


    //Set up our connection
    $connectionInfo = new ConnectionInfo();
    $connectionInfo->GetConnection();

    if (!$connectionInfo->conn)
    {
        //Connection failed
        echo 'No Connection';
    }

    else
    {
        //Create query to retrieve all contacts
        $query = 'SELECT Numero_Leccion,Titulo_Leccion,Ejemplo_Leccion FROM leccion';

        $stmt = sqlsrv_query($connectionInfo->conn, $query);

        if (!$stmt)
        {
            //Query failed
            echo 'Query failed';
        }

        else
        {
            $contacts = array(); //Create an array to hold all of the contacts
            //Query successful, begin putting each contact into an array of contacts

            while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
            {
                //Create an associative array to hold the current contact
                //the names must match exactly the property names in the contact class in our C# code.
                $contact = array("Numero_Leccion"=>$row['Numero_Leccion'],"Titulo_Leccion"=>$row['Titulo_Leccion'],"Ejemplo_Leccion"=>$row['Ejemplo_Leccion']);              
                //Add the contact to the contacts array
                array_push($contacts, $contact);
            }
            //Echo out the contacts array in JSON format
            echo json_encode($contacts);
        }
    }
?>

2 个答案:

答案 0 :(得分:0)

error_reporting(E_ALL & ~E_NOTICE); ini_set('display_errors', '1');放在脚本的顶部,看看是否有错误

(摘自Why echoing JSON encoded arrays won't produce any output

答案 1 :(得分:0)

试试这个:

while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
    $contacts[] = array("Numero_Leccion"=>$row['Numero_Leccion'],"Titulo_Leccion"=>$row['Titulo_Leccion'],"Ejemplo_Leccion"=>$row['Ejemplo_Leccion']);              
}
header('Content-Type: application/json');
echo json_encode($contacts);