convert array from" file_get_contents()"回到阵列

时间:2014-03-11 13:02:46

标签: php arrays file-get-contents

当我尝试使用

从API获取数据时
file_get_contents("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDINR%22)&format=json&env=store://datatables.org/alltableswithkeys&callback=");

我把结果作为一个字符串。有没有办法将它转换回数组? 我得到的字符串是

string(202) "{"query":{"count":1,"created":"2014-03-11T13:00:31Z","lang":"en-US","results":{"rate":{"id":"USDINR","Name":"USD to INR","Rate":"60.99","Date":"3/11/2014","Time":"9:00am","Ask":"61.00","Bid":"60.98"}}}}"{"error":"","msg":""}

请帮帮我....

2 个答案:

答案 0 :(得分:5)

在您的请求中,您要求返回的格式为JSON - 已编码(通过format=json参数),因此您只需使用json_decode将响应解码为数组:< / p>

$response = file_get_contents("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDINR%22)&format=json&env=store://datatables.org/alltableswithkeys&callback=");
$response = json_decode($response, true);

// Parse the array as you would any other

答案 1 :(得分:0)

你有一个JSON答案,所以jo需要dekode。

<?php
$s =  file_get_contents("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDINR%22)&format=json&env=store://datatables.org/alltableswithkeys&callback=");$data = 
$data = json_decode($s,true);
?>

并且$ data变量将是一个数组。