user3825694 user3825694 - 2 months ago 20
JSON Question

Json str_replace

I am trying to make an str replace to a json file.
for some reason its not working.
This is the script:

$json = file_get_contents ("http://www.klh-dev.com/adom/alert/alerts.json");

$area = array("228",
"157");
$place = array("bad",
"good");

$change = str_replace($area, $place, $json);


I have tried to create a string that has the exact same content as the json file has and it worked.

$test = '{ "id" : "1405254580565", "title" : "Testing ", "data" : ["157"] }';

$area = array("228",
"157");
$place = array("bad",
"good");

$change = str_replace($area, $place, $test);


So why does it work with the string, and not with the json file?

EDIT:
Ok I tried to use decoding

$json = file_get_contents ("http://www.oref.org.il/WarningMessages/alerts.json");

var_dump(json_decode($json));


But for some reason its not working.
But when I try to input the json code manually it works fine

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

Answer

There is actually a much easier way to read this JSON, by using iconv().

// Query Home Front Command API
// Accessible only from Israel    
$json = @file_get_contents( 'http://www.oref.org.il/WarningMessages/alerts.json' );

// Got a response from the API?    
if ( $json ) {
    // Convert from UTF-16 to UTF-8    
    $json = @iconv( 'UTF-16', 'UTF-8', $json );

    // Succeeded?    
    if ( $json ) {
        // Trim JSON of whitespace    
        $json = trim( $json );

        // Convert JSON string to object    
        $json = @json_decode( $json );

        // Output JSON object           
        var_dump( $json );
    }
}
Comments