frasta frasta - 4 months ago 20
JSON Question

Printing emails from json objects with php

I am trying to simply write all of these emails in a text file seperated with a comma like so

email1@email.com, email2@email.com, etc


I am new to php and now sure why I keep getting this parse error. I tried many things with all fails. Please help

<?php
$s = '{
"-KNWTldOkA_WkT50a_aS" : {
"Email" : "user@test.com",
"num" : 3

},
"-KNi22_ZC7PlnDJkR4px" : {
"Email" : "userEmailx@gmail.com",
"num" : 10

}
}';

$j = json_decode($s, true);
echo $j['-KNWTldOkA_WkT50a_aS']['Email'] . ',';

$file = fopen("emails.txt","w");

foreach ($j as $a) {
var email = $a['Email'] . ',';
fwrite($file, email);
}

fclose($file);

Answer

You had several syntax errors in your code.

The correct code is:

<?php

$s = '{
     "-KNWTldOkA_WkT50a_aS" : {
     "Email" : "personsemail@gmail.com",
     "id" : 3
 },
   "-KNi22_ZC7PlnDJkR4px" : {
   "Email" : "personsemail@gmail.com",
   "id" : 10
 }
}';


$j = json_decode($s,True);

$emails = array();
foreach ($j as $a) {
    $emails[] = $a['Email'];
}
$file = fopen( __DIR__ . DIRECTORY_SEPARATOR ."emails.txt","w");
fwrite($file, implode(',', $emails ));
fclose($file);

?>

File emails.txt will be saved in the same directory as your php file with this code.