Reputation: 45
How can I json_decode()
result of file_get_contents
?
Here is my code.
$resp = file_get_contents('https://auth.login.yahoo.co.jp/yconnect/v1/token', false, $context);
echo "check1 <br />";
var_dump($resp);
$json = json_decode($resp);
echo "check2 <br />";
var_dump($json);
echo $json['access_token'];
The result is here
check1
string(744) "{"access_token":"j9MqiEM.lKjepCGMFdKufPw1UBK_gAlG6qFxvMxHJwbopXfo9LpLUyT1z.YxwFBSydvVSMOqzVI4fX_ZVLVROlNf7ARr08s2tkFMb5_TNq.wp1MmoQm3wJaqF9gxpeQbEz4GYuGJSbDKJTw8LA_XoBNcEbL0ZDeozFEgYxII8gqi_Nfi7UhM5bd7gqV6Sp17rCECQAauZj_jJa6jyADS3me3UYxIKJB2tCJpRM.xCzVhjRWEZPqNiUI5NikXRANrSiTyn_6Z72u2ptW3vnK918TqpPBAdj.P1O5uJAZgKEmLMZLSBEIWIEOUPTJaSvI3qxxk1ItXI_5sZDAQuw.86R3eaSIolGHqWTvpLk3WqnqBvtk6w6qIVcZgJrTFxnjx_x1ijJhKACcnY.jYp6kpxMihe8hOrTEyVj4Swhmq4RUWDhAfIQDNNju5dJCqW82QyYNCQdf0IMW7uIRSvHK1FmTGrEWMv4tpojLtJEf5vnKaDbrxZ0.AB9OSRwhzMkUYkgbiEVCwqyxCy_oEQBB0uVuAL8fOYidPrqv8m.A29j7S9d3Cb7DFh7pQJJGkLzljcC4VkEZADLiPnq_aLZuy0ehb_aTLBoHZ0IUL","token_type":"bearer","expires_in":"3600","refresh_token":"ABrQBFdlHzed4sc.aHygqG0faENua5L865UMVglio2hkbIJAnbY-"}"
'check1' is there and token value is result of var_dump($resp);
but 'check2' not working.
So I think $json = json_decode($resp);
is fail.
How do I decode this?
Thanks.
Upvotes: 1
Views: 264
Reputation: 6563
This is encoding issue. You have BOM in your response that is not shown by var_dump
but is not properly treated by json_encode
.
If you try to do next:
$s = "\xEF\xBB\xBF".'{"access_token":"j9MqiEM.lKjepCGMFdKufPw1UBK_gAlG6qFxvMxHJwbopXfo9LpLUyT1z.YxwFBSydvVSMOqzVI4fX_ZVLVROlNf7ARr08s2tkFMb5_TNq.wp1MmoQm3wJaqF9gxpeQbEz4GYuGJSbDKJTw8LA_XoBNcE$
var_dump($s);
var_dump(json_decode($s));
You will get exact same result as in your response.
You can play around with headers to make sure that you are using utf-8
encoding during request or you can get rid of BOM
by:
$bomBinString = pack('H*','EFBBBF');
$s = preg_replace("/^$bomBinString/", '', $s);
Upvotes: 1