Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

php - String appears to be valid JSON, but `json_decode()` returns NULL

I think I've found where the error lies:

    $convertJSON = file_get_contents("http://www.google.com/ig/calculator?hl=en&q=" . $currencyValue . $currencySelectValue . "%3D%3FUSD", true);
    var_dump($convertJSON);
    $convertArr = json_decode($convertJSON, true);
    var_dump($convertArr);

I do that to debug, and I get this result (I entered 555 and Euros):

string(68) "{lhs: "555 Euros",rhs: "796.64700 U.S. dollars",error: "",icc: true}"
NULL

So it seems that the PHP function to decode the JSON object is doing something wrong somewhere. Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not a direct response to this question, but an issue I spent a few hours trying to resolve.

If you are attempting to decode JSON that came from a remote file via CURL, and if that file is in UTF-8 format, the beginning of the file may have the following characters (which breaks json_decode():



Which you will not see with the naked eye, only via htmlentities(); I have no idea why they are there, I traced this all the way to curl_exec(), thinking that maybe they were being added there. In any case, those little bastards were being added only when file is in UTF-8 format.

So, assuming you have no control over the encoding of the source file, you can do something like this before passing the string into json_decode():

$encoding = mb_detect_encoding($json);

if($encoding == 'UTF-8') {
  $json = preg_replace('/[^(x20-x7F)]*/','', $json);    
}    

print_r(json_decode($json));

I hope I save somebody some time, it took me a few hours of tracing to figure out that's what was happening.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...