chronotrigga
chronotrigga

Reputation: 609

Decode JSON to PHP

I have a .txt file called 'test.txt' that is a JSON array like this:

  [{"email":"[email protected]","createdate":"2016-03-23","source":"email"}]

I'm trying to use PHP to decode this JSON array so I can send my information over to my e-mail database for capture. I've created a PHP file with this code:

 <?php 

 $url = 'http://www.test.com/sweeps/test.txt';
 $content = file_get_contents($url);
 $json = json_decode($content,true);

 echo $json; 


 ?>

For some reason, it's not echoing the decoded JSON when I visit my php page. Is there a reason for this and can anyone shed some light? Thanks!

Upvotes: 1

Views: 240

Answers (2)

Eihwaz
Eihwaz

Reputation: 1234

You'll need to split that json string into two separate json strings (judging by the pastebin you've provided). Look for "][", break there, and try with any of the parts you end up with:

$tmp = explode('][', $json_string);

if (!count($tmp)) {
    $json = json_decode($json_string);

    var_dump($json);
} else {
    foreach ($tmp as $json_part) {
        $json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');

        var_dump($json);
    }
}

Upvotes: 1

RiggsFolly
RiggsFolly

Reputation: 94682

You use echo to print scalar variables like

$x = 'Fred';
echo $x;

To print an array or object you use print_r() or var_dump()

$array = [1,2,3,4];
print_r($array);

As json_decode() takes a JSON string and converts it to a PHP array or object use print_r() for example.

Also if the json_decode() fails for any reason there is a function provided to print the error message.

<?php 
 $url = 'http://www.test.com/sweeps/test.txt';
 $content = file_get_contents($url);
 $json = json_decode($content,true);

 if ( json_last_error() !== JSON_ERROR_NONE ) {
    echo json_last_error_msg();
    exit;
 }

Upvotes: 1

Related Questions