Как получить конкретное содержимое массива (?) С помощью php? - PullRequest
0 голосов
/ 08 июня 2019

Так что я думаю, что у меня есть массив, содержащий много данных из API (хотя может быть json, но я не уверен: https://bitebtc.com/api/v1/market),, и я хочу извлечь некоторые конкретные данные, такие как «процент» .

Я попробовал 3 способа относительно аналогичного использования метода json_decode (), но ничего не получилось: / Вот один из них:

<?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...

1 Ответ

0 голосов
/ 09 июня 2019

Посетите документы для 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, чтобы проверить его ...

...