无法从我的php webservice收到json_decode输出?

时间:2011-07-25 08:25:47

标签: php json

Webservice代码:

function login($uname)
        {   

            $id=1;
            $link = mysql_pconnect("localhost", "root", "root") or die("Could not connect");
            mysql_select_db("sparq",$link) or die("Could not select database");
            $sql=mysql_query("select username,password from user_login where user_id=1");
            //$result = mysql_query($query);
            $arr = array();
            while($obj = mysql_fetch_object($sql)) 
                {
                    $arr[] = $obj;
                    }
           // $obj = mysql_fetch_object($sql);
           header("Content-type: application/json");
           echo json_encode($arr);
        }

来自客户的代码:

$url="http://localhost/web.php";
if (isset($_POST['Login']))
    {

            $ch = curl_init($url); // Initialize a CURL session
            curl_setopt($ch, CURLOPT_HEADER, 0); // options for a CURL transfer
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,"username=".$username );
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $data = curl_exec($ch); // Perform a CURL session
            curl_close($ch); 
            $arr =array();
            $arr=json_decode($data,true);
            echo 'I am here';    //echo1
            echo $data;   //echo2

            echo $arr[0]->username; //echo3

我得到以下输出:

I am here //echo1
[{"username":"akhilnk@gmail.com","password":"asdf123"}]  //echo2
Notice: Trying to get property of non-object in F:\xampp\htdocs\webtest\login.php on line 38  //echo3

2 个答案:

答案 0 :(得分:3)

此:

echo $arr[0]->username;

应该是:

echo $arr[0]['username'];

而且:

$arr = array();
while($obj = mysql_fetch_object($sql)) {
  $arr[] = $obj;
}

应该是:

$arr = array();
while($row = mysql_fetch_assoc($sql)) {
  $arr[] = $row;
}

你不能通过json发送php对象。 javascript(和json)调用对象的是php中的关联数组。

答案 1 :(得分:0)

替换:echo $ arr [0] - > username;通过$ arr [0] ['用户名'];