Nidhin
Nidhin

Reputation: 1838

Unexpected json string when json_encode array having object's value in php

Object having a value var $error_code="100"; I can set this value inside a function as

$this->error_code=$simpleXml->error_code;  // eg:214

I can create its object and print value using json_encode as

 echo $obj->error_code; //print value 214
 $code=$obj->error_code;
 $set=array("error_code" => $code,"message" =>"topup failed");
 echo json_encode($set);

I got response as

214 {"error_code":{"0":"214"},"message":"topup failed"}

but I expect output as

{"error_code":"214","message":"topup failed"}

what is the actual problem for getting

{"0":"214"} 

on output even if $code print value 214 ?

Upvotes: 1

Views: 366

Answers (2)

Michael Christensen
Michael Christensen

Reputation: 195

Instead of :

echo $obj->error_code; //print value 214
$code=$obj->error_code;
$set=array("error_code" => $code,"message" =>"topup failed");
echo json_encode($set);

Just use:

$code = $obj->error_code;
echo json_encode(array("error_code" => $code,"message" =>"topup failed"));

Remove the other lines, they are unnecessary.

Edit: Add the [0] after $obj->error_code

Upvotes: 0

viral
viral

Reputation: 3743

Change this line,

$code=$obj->error_code;

to

$code=$obj->error_code->0;

Also remove

echo $obj->error_code;

to get

{"error_code":"214","message":"topup failed"}

Upvotes: 1

Related Questions