首页 > 解决方案 > 如何使用 php 获取数组(?)的特定内容?

问题描述

所以我想我有一个包含来自 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...

标签: phparraysjsondecodefile-get-contents

解决方案


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

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 的计算机上进行测试...


推荐阅读