使用PHP中的文字符号/对象初始值设定项解释Javascript对象

时间:2012-10-22 10:41:59

标签: php javascript

我创建了一个PHP脚本,使用curl从远程网站获取对象初始化程序,对象看起来像这样

{'403' : {'3' : { qin : 144, qout : 52}, '4' : { qin : 143, qout : 86}, '5' : { qin : 144, qout : 79}, '6' : { qin : 143, qout : 93}, '7' : { qin : 144, qout : 78} }

¿PHP中是否有一个函数来解释这个或我需要使用正则表达式?

JSON不是有效的,但它是一个有效的Javascipt文字符号。

1 个答案:

答案 0 :(得分:0)

不在生产中使用而是尝试获取有效的json输出

$json = "{'403' : {'3' : { qin : 144, qout : 52}, '4' : { qin : 143, qout : 86}, '5' : { qin : 144, qout : 79}, '6' : { qin : 143, qout : 93}, '7' : { qin : 144, qout : 78} }" ;

$json = preg_replace("/'(\w+)'/", '$1', $json); //remove all single quote
$json = preg_replace("/\s*([a-zA-Z0-9_]+)/", ' "$1"', $json);
$json .= "}"; // Missing End

var_dump($json,json_decode($json));

输出

object(stdClass)[1]
  public '403' => 
    object(stdClass)[2]
      public '3' => 
        object(stdClass)[3]
          public 'qin' => string '144' (length=3)
          public 'qout' => string '52' (length=2)
      public '4' => 
        object(stdClass)[4]
          public 'qin' => string '143' (length=3)
          public 'qout' => string '86' (length=2)
      public '5' => 
        object(stdClass)[5]
          public 'qin' => string '144' (length=3)
          public 'qout' => string '79' (length=2)
      public '6' => 
        object(stdClass)[6]
          public 'qin' => string '143' (length=3)
          public 'qout' => string '93' (length=2)
      public '7' => 
        object(stdClass)[7]
          public 'qin' => string '144' (length=3)
          public 'qout' => string '78' (length=2