php – not saved to json file (php+redis)?

not saved to json file (php+redis)?… here is a solution to the problem.

not saved to json file (php+redis)?

Why is the data not recorded in the json file?
Why not create this file?
I write code in the Linux operating system
I run it locally

$r = new Redis(); 
$r->connect('127.0.0.1', 6379); 

$key="info_users";

$r->hmset($key, [
    'id' => 1,
    'username' => 'sajjad10ss',
    'password' => '1q2w3edxsz0',
    'fulname' => 'sajjad kazemi',
    'email' => '[email protected]',
]);
  $data=array();
  $data[] = $r->hgetall($key);

$json= json_encode($data, JSON_PRETTY_PRINT);

header('Content-type: text/javascript');
if (file_put_contents('xldata.json', $json))
{
    echo "Saved json to file...";
  }
else{
    echo "Oops! Error saving json...";
  }

Why give out the following? Oops! Error saving json…;

Solution

This is most likely a permissions issue. You can check if this is the problem using is_writable().

You should chown the directory where the script is run, e.g. chown nginx:nginx xldata.json if it is in nginx .

I’ve also changed the syntax slightly for your file_put_contents() failure.

$r = new Redis(); 
$r->connect('127.0.0.1', 6379); 

$key="info_users";

$r->hmset($key, [
    'id' => 1,
    'username' => 'sajjad10ss',
    'password' => '1q2w3edxsz0',
    'fulname' => 'sajjad kazemi',
    'email' => '[email protected]',
]);
$data=array();
$data[] = $r->hgetall($key);

$json= json_encode($data, JSON_PRETTY_PRINT);

if (! is_writable('xldata.json') {
    die('Unable to write to xldata.json');
}
file_put_contents('xldata.json', $json) or die('Could not write to json file');

header('Content-type: text/javascript');
echo $json;

Related Problems and Solutions