【问题标题】:How to get specific content of an array (?) using php?如何使用 php 获取数组(?)的特定内容?
【发布时间】:2019-10-23 16:03:04
【问题描述】:

所以我认为我有一个数组,其中包含来自 API 的大量数据(虽然可能是 json,但我不确定:https://bitebtc.com/api/v1/market),我想提取一些特定数据,例如“百分比”。

我使用 json_decode() 方法尝试了 3 种相对相似的方法,但没有任何效果:/ 这是其中之一:

<?php
  $string = "https://bitebtc.com/api/v1/market";
  $decoded = file_get_contents($string);
  $percent = $decoded->percent;
  echo $percent;

As you can see in the link, the expected output would be something like 1.3 or at least a floating number between 0 and 10, but I got nothing, or a php notice: Trying to get property of non-object; since it is not an error I guess the problem doesn't come from the non-object property thing...

【问题讨论】:

  • 如果$decoded === null,您可能有解码问题。尝试var_dump$decoded。 (您可能需要从该 url 获取,json_decode 需要一个有效的 JSON 字符串。)
  • 上面的代码将 $data 设置为一个字符串,即 url,它没有获取 json 结果。您正在尝试将 url 解码为 json 字符串。快速而肮脏的方法是使用 $json = file_get_contents($url);
  • @Progrock 确实 $decoded 是 NULL!这意味着我的 json_decode() 没有返回任何东西......嗯,我应该使用 fopen() 还是类似的东西呢?也许是 file_get_content ?
  • 是的,试试file_get_contents
  • 你没有对 uri 做任何事情——它实际上只是一个字符串,而不是一个数组。您需要先连接到该 uri..

标签: php arrays json decode file-get-contents


【解决方案1】:

请访问file_get_contents() 的文档以获取有关如何传递此 api 所需的标头 (Content-Type: application/json) 的信息。

curl -X GET 'https://bitebtc.com/api/v1/markets' -H 'Content-Type: application/json'

这可能会对您返回的内容产生很大影响(!)... 使用文档中的示例代码适用于您的情况,我们提出了如下内容:

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Content-Type: application/json\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('https://bitebtc.com/api/v1/markets', false, $context);

// now print out the results so you can see what you're working with (should be a huge JSON string)
print $file;

// decode it and var dump it to see how to work with it
$decoded = json_decode($file);
var_dump($decoded);

?>

您可能必须使用此示例;我没有在安装了 PHP 的电脑上测试它...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多