简体   繁体   中英

json_decode is returning string instead of array/object if the original content is from external server

I need to fetch a JSON content from an external site, but for some strange reason I can't make it an array or object, instead json_decode is returning it as string. If I copy the same original content in full length into a variable and use that instead then it works correctly: json_decode turns it into object/array.

function isJson($string) {
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

$url = "http://www.igetthestufffromhere.com";

$response = trim(strip_tags(file_get_contents($url))); 

I have tried without trim and strip_tags and also tried with CURL and the result is the same.

//$response ="[{\"SaleDate\":\"2015-10-22T14:09:00\",\"End\":\"2015-11-22T00:00:00\",...SHORTENED A LOT..\"ChildList\":null}],\"ExName\":\"SELVÄ\",\"SomeName\":\"\"}]";

echo "ENCODING:".mb_detect_encoding($response); returns: utf-8 every time

if( isJson($response) ){
    echo "Yes it is JSON"; // This is TRUE in both cases (local variable and fetched).
}

$json = json_decode($response, true);

var_dump($json); 

var_dump returns: string(302087) ""[{\\"SaleDate\\"....]"" when I get the response from that other domain, but when I use the local variable with exactly same manually copy-pasted content it returns: array(139) { [0]=> array(34) { ["SaleDate ...

Edit: I don't understand why I just got a downvote, I have tried to solve this for about 5 hours, I pasted all the code needed to answer and there is a real problem here.. so what's the matter with my question!? I shouldn't have this problem?! My first question in this site too.

Ok the problem was answered by @deceze

It was because the JSON was double-decoded. So it needed to be double-encoded. Here is the working code:

function isJson($string) {
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

$url = "http://www.igetthestufffromhere.com";

$response = trim(strip_tags(file_get_contents($url))); 
$i=0;
while (is_string($response)){ //if is still string
    $response = json_decode($response); // decode to object
    if( $i>3 ){  // stop if still not working
        break 1;
    }
    $i++;
}

var_dump($json); // is always JSON object

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