简体   繁体   中英

2 JSON. Only 1 work. json_decode php

I seriously got gray hair.

I would like to echo the [ask] data for https://api.gdax.com/products/btc-usd/ticker/

But it's return null.

When i try with to use another API with almost the same json, it work perfect.

This example works

<?php 

$url = "https://api.bitfinex.com/v1/ticker/btcusd";
$json = json_decode(file_get_contents($url), true);
$ask = $json["ask"];
echo $ask;

This example return null

<?php 

$url = "https://api.gdax.com/products/btc-usd/ticker/";
$json = json_decode(file_get_contents($url), true);
$ask = $json["ask"];
echo $ask;

Anybody there has an good explanation, whats wrong with the code returning null

the server of that null result is preventing php agent to connect thus returning http 400 error. you need to specify a user_agent value to your http request.

eg

$ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36';
$options  = array('http' => array('user_agent' => $ua));
$context  = stream_context_create($options);

$url = "https://api.gdax.com/products/btc-usd/ticker/";
$json = json_decode(file_get_contents($url, false, $context), true);
$ask = $json["ask"];
echo $ask;

you can also use any user_agent string you want on the $ua variable, as long as you make sure that your target server allows it.

You can't access this URL without passing arguments. It happen some time when the host is checking from where the request come.

$ch = curl_init();
$header=array('GET products/btc-usd/ticker/ HTTP/1.1',
    'Host: api.gdax.com',
    'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language:en-US,en;q=0.8',
    'Cache-Control:max-age=0',
    'Connection:keep-alive',
    'Host:adfoc.us',
    'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36',
    );

    curl_setopt($ch,CURLOPT_URL,"https://api.gdax.com/products/btc-usd/ticker/");
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,0);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
    $result=curl_exec($ch);

Then you can use json_decode() on $result !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM