【问题标题】:decode json in php [duplicate]在php中解码json [重复]
【发布时间】:2011-12-24 00:08:17
【问题描述】:

我正在使用 Google 的货币计算 API。它返回 json。我可以将 URL 内容转换为字符串,但是如何在 php 中解析它?我正在尝试返回“rhs”值。

    $string='{lhs: "1 Euro",rhs: "1.3067 U.S. dollars",error: "",icc: true}'; 
    $rhs=?????
    echo $rhs; 

【问题讨论】:

标签: php json api


【解决方案1】:

json_decode() 是您将使用的。

$data = json_decode($string);
$rhs = $data->rhs;

【讨论】:

    【解决方案2】:
    $string='{lhs: "1 Euro",rhs: "1.3067 U.S. dollars",error: "",icc: true}'; 
    $json=json_decode($string);
    echo $json->rhs;
    

    http://us.php.net/json_decode

    【讨论】:

      【解决方案3】:

      没什么大不了的:

      $obj = json_decode($string);
      $rhs = $obj->rhs;
      

      【讨论】:

        【解决方案4】:

        使用json_decode

        $rhs = json_decode($string);
        // $rhs is an object now.
        

        【讨论】:

        • 不,不传递 TRUE 作为第二个参数,$rhs 现在是一个对象,而不是字符串。
        【解决方案5】:

        使用PHP的json_decode()函数:

        $string      = '{lhs: "1 Euro",rhs: "1.3067 U.S. dollars",error: "",icc: true}';
        $json_object = json_decode($string);
        $rhs         = $json_array->rhs;
        
        echo $rhs; 
        

        【讨论】:

        • 与 Indranil 类似,使用 json_decode() 而第二个参数不为 true 意味着 $json_array 是 Object 类型,而不是 Array 类型。您必须使用 -> 语法访问对象的成员。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-14
        • 1970-01-01
        • 1970-01-01
        • 2013-09-03
        • 1970-01-01
        相关资源
        最近更新 更多