【问题标题】:convert array got as string from "file_get_contents()" back to array [duplicate]将数组作为字符串从“file_get_contents()”转换回数组[重复]
【发布时间】:2014-04-15 02:43:23
【问题描述】:

当我尝试使用

从 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":""}

请帮帮我....

【问题讨论】:

标签: php arrays file-get-contents


【解决方案1】:

在您的请求中,您要求返回的格式为JSON 编码(通过format=json 参数),因此您可以使用json_decode 将响应解码为数组:

$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

【讨论】:

  • 感谢您的快速回复... :)
  • 很高兴为您提供帮助。如果它被证明有用,请随时接受答案:)
  • 需要有 15 声望才能接受它.. :(
【解决方案2】:

您在此处有一个 JSON 答案,因此您需要对其进行解码。

<?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 变量将是一个数组。

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 1970-01-01
    • 2013-12-05
    • 2021-08-20
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多