【问题标题】:PHP add data to json filePHP将数据添加到json文件
【发布时间】:2014-08-15 14:47:10
【问题描述】:

我尝试将数据添加到 json 文件中。

第一次尝试:

$filename = "$root/nachrichten/bla.json";

$neueartikel = json_decode(file_get_contents($filename), true); /*until here everything works, I can loop the file*/

$neueartikel[] = array('titel' => 'bla',
                    'bild' => 'bla',
                    'url' => 'bla',
                    'ID' => 'bla',
                    'bildserver' => 'bla'); 

file_put_contents('$root/nachrichten/bla.json', json_encode($neueartikel);

第二次尝试:

$filename = "$root/nachrichten/bla.json";

$neueartikel = json_decode(file_get_contents($filename), true);

$neu[] = array('titel' => 'bla',
                    'bild' => 'bla',
                    'url' => 'bla',
                    'ID' => 'bla',
                    'bildserver' => 'bla');

$result = array_merge($neueartikel, $neu);

file_put_contents('$root/nachrichten/bla.json', json_encode($result);

我怎样才能做到这一点????

更新:

我也试了一下 PotatoIng 说的:

$filename = "$root/nachrichten/bla.json";

    $temparray = json_decode(file_get_contents($filename), true);

    $neu = array('titel' => 'bla',
                        'bild' => 'bla',
                        'url' => 'bla',
                        'ID' => 'bla',
                        'bildserver' => 'bla');

    array_push($temparray, $neu);

    file_put_contents("$root/nachrichten/bla.json", json_encode($temparray);

还是什么都没有(忽略这个文本我需要添加一些否则我无法提交-.-)

【问题讨论】:

  • 您有写入文件的权限吗?更具体地说,PHP 脚本的所有者/用户是否有权写入文件?

标签: php json merge


【解决方案1】:

基本 PHP:'-quoted 字符串插入变量:

file_put_contents('$root/nachrichten/bla.json', json_encode($neueartikel);
                  ^^^---

您的代码正在尝试将您的文件写入到名称为 $ro 等的目录中......

改用"-quoted 字符串。

【讨论】:

  • 我现在这样尝试:file_put_contents("$root/nachrichten/bla.json", json_encode($neueartikel); 还有:file_put_contents($root . "/nachrichten/bla.json" , json_encode($neueartikel); 但它仍然无法正常工作:/
  • 好吧,$root 是在哪里定义的,它的值是多少?
  • $root = realpath($_SERVER["DOCUMENT_ROOT"]);它在代码之上,我可以循环 $neueartikel: $filename = "$root/nachrichten/bla.json"; $neueartikel = json_decode(file_get_contents($filename), true);所以我想这不是问题
  • 文件可能是777,但是它所在的目录呢?
  • 这也是777 我想我必须联系我的主人??到现在为止从来没有问题oO
【解决方案2】:
$data[] = $_POST['data'];

$inp = file_get_contents('results.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData;

由“Tim”在Append data to a .JSON file with PHP 上回答

【讨论】:

    猜你喜欢
    • 2014-11-11
    • 1970-01-01
    • 2011-12-15
    • 2022-11-16
    • 2022-01-13
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多