0

Im really new in json code, even javascript code but I got this so far. I'm able to get json data from a local file with the same information but not from this external URL: https://s3.amazonaws.com/dolartoday/data.json

This is my code:

<?php

$json = file_get_contents("https://s3.amazonaws.com/dolartoday/data.json", 'jsonp');
$data = json_decode($json, true);

echo $data['USD']['dolartoday'];

?>

Expected result, something like this: 6124.24

Note: this code is ok, I get data from a local file with the same values but I cant fetch json data from this external URL specifically. I also added 'jsonp' but that didnt work.

2 Answers 2

5

Your JSON document on S3 is invalid.

JSON is required to be in UTF-8, but you appear to have extended ASCII characters in it instead.

Proper error checking would have revealed this.

$data = json_decode($json, true);
if (is_null($data)) {
    echo json_last_error_msg();
    die;
}

which would have printed

Malformed UTF-8 characters, possibly incorrectly encoded
Sign up to request clarification or add additional context in comments.

4 Comments

If on >PHP 7.3 then you can use the flag JSON_THROW_ON_ERROR
If on PHP 7.2 or higher, you can pass the JSON_INVALID_UTF8_IGNORE option
Thanks @Stephen Clouse I didnt know that.
I should clarify that other encodings have been allowed in the past, but UTF-8 is the only encoding that has been part of the spec for its entire lifetime, thus it is the only guaranteed interoperable encoding. The most recent revision of the JSON spec (RFC 8259) clarifies this and essentially mandates UTF-8 as the only supported encoding.
0

Thanks to @Stephen's clarification I found a solution to my problem.

<?php
$json = file_get_contents("https://s3.amazonaws.com/dolartoday/data.json", 'jsonp');
$utf8 = utf8_decode($json); //decode UTF-8
$data = json_decode($utf8, true);

echo $data['USD']['dolartoday'];
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.