1

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!

6
  • 1
    It's not JSON after decode, its a PHP array: print_r($json); and/or loop over it and echo the elements. Commented Mar 23, 2016 at 17:19
  • 1
    $foo = array('a','b'); echo $foo outputs the literal word Array, not the contents of the array. you cannot echo/print arrays directly. Commented Mar 23, 2016 at 17:20
  • This json string is missing a quote in the "email" field. Fix that, and it decodes just fine. Commented Mar 23, 2016 at 17:22
  • It seems like the Json is missing an extra quote that can be causing the error. (before the email field) Commented Mar 23, 2016 at 17:23
  • Apologies, I actually handwrote the JSON because it's three entries. The full version is here: pastebin.ca/3409494 Commented Mar 23, 2016 at 17:28

2 Answers 2

1

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;
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Any reason why var_dump will show a NULL and print_r won't show anything? My actual JSON entries from woobox is here: pastebin.ca/3409494
If you run that JSON String through the json lint validator you will see that it is not valid JSON. Or use the json_last_error() code I added to the answer
1

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);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.