【发布时间】: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;
【问题讨论】:
我正在使用 Google 的货币计算 API。它返回 json。我可以将 URL 内容转换为字符串,但是如何在 php 中解析它?我正在尝试返回“rhs”值。
$string='{lhs: "1 Euro",rhs: "1.3067 U.S. dollars",error: "",icc: true}';
$rhs=?????
echo $rhs;
【问题讨论】:
json_decode() 是您将使用的。
$data = json_decode($string);
$rhs = $data->rhs;
【讨论】:
$string='{lhs: "1 Euro",rhs: "1.3067 U.S. dollars",error: "",icc: true}';
$json=json_decode($string);
echo $json->rhs;
【讨论】:
没什么大不了的:
$obj = json_decode($string);
$rhs = $obj->rhs;
【讨论】:
使用json_decode
$rhs = json_decode($string);
// $rhs is an object now.
【讨论】:
使用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;
【讨论】:
json_decode() 而第二个参数不为 true 意味着 $json_array 是 Object 类型,而不是 Array 类型。您必须使用 -> 语法访问对象的成员。