如何解码存储在php中的变量中的json字符串

时间:2014-11-06 09:29:03

标签: php json

我有一个用JSON编码的响应。存储在变量中并尝试解码。但它没有显示任何东西。 代码在这里

echo $response; //prints response like 

({" OrderStatus":" REJECT"," OrderID":""," PONumber": "","拒绝原因":" INVALID_FLD_VALUE您为以下字段输入了无效字段值41111:ccnumber"," AUTHCODE" :""," ShippingCost":""," HandlingCost":""});

//Trimming braces etc
$routes = ltrim($response, '('); //left trim
$routes_comp= rtrim($routes, ');'); //right trim
echo "<br/>"; 
  echo $routes_comp;

  //decoding here 
   $jsoni=json_decode($routes_comp);
   $var= $jsoni->OrderStatus;
    print_r($var);

      exit;

我想要订单状态值,但它没有显示任何东西。实际的方式是什么?。

2 个答案:

答案 0 :(得分:1)

使用json_decode($ routes_comp,true); - 错了

修改 测试你的代码创建响应变量,如你所说;

$response = '({ "OrderStatus" : "REJECT", "OrderID" : "","PONumber" :"", "Reject Reason" : "INVALID_FLD_VALUE You have entered an Invalid Field Value 41111 for the following field: ccnumber", "AUTHCODE" : "", "ShippingCost" : "", "HandlingCost" : ""});';

$routes = ltrim($response, '('); //left trim
$routes_comp= rtrim($routes, ');'); //right trim
echo "<br/>"; 
  echo $routes_comp;

  //decoding here 
   $jsoni=json_decode($routes_comp);
   $var= $jsoni->OrderStatus;
    print_r($var);

      exit;

得到了这个

<br/>{ "OrderStatus" : "REJECT", "OrderID" : "","PONumber" :"", "Reject Reason" : "INVALID_FLD_VALUE You have entered an Invalid Field Value 41111 for the following field: ccnumber", "AUTHCODE" : "", "ShippingCost" : "", "HandlingCost" : ""}REJECT

所以我认为$ response可能会以某种方式被破坏。你可以在修剪之前把var_dump再次测试吗?

答案 1 :(得分:1)

完成这项技术。 实际上错误是json字符串之间的空格。

     $routes_comp=preg_replace('/\s+/', '',$routes_comp);
     $json=json_decode(stripslashes($routes_comp));
     $os=$json->OrderStatus;