开发者

Unable to json_decode output received from my php webservice?

Webservice code:

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

Code from client:

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

            $ch = curl_init($url); // Initialize a CURL sessio开发者_如何学运维n
            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 getting the below output:

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


This:

echo $arr[0]->username;

Should be:

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

And this:

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

Should be:

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

You can't send php objects over json. What javascript (and json) call an object is an associative array in php.


Replace: echo $arr[0]->username; by $arr[0]['username'];

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜