So I think I have an array containing a lot of data from an API (might be json though but I'm not sure : https://bitebtc.com/api/v1/market), and I want to extract some specific data such as the 'percent'.
I tried 3 ways relatively similare using json_decode() method but nothing worked :/ Here's one of them:
<?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...
Visit the docs for file_get_contents() for information on how to pass the header (Content-Type: application/json
) that this api requires.
curl -X GET 'https://bitebtc.com/api/v1/markets' -H 'Content-Type: application/json'
This probably makes quite a bit of difference in what you get back(!)... Using the sample code from the docs to apply to your situation, we come up with something like this:
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Content-Type: application/json
"
)
);
$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);
?>
You may have to work with this example; I'm not on a computer with PHP installed to test it...