dtdfj08626 2014-08-15 14:47 采纳率: 0%
浏览 126

PHP将数据添加到json文件

I try to add data to a json file.

First try:

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

Second try:

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

How can I do this right????

UPDATE:

I also tryed what PotatoIng sayd:

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

Still nothing (ignore this text I need to add some or else I can't submit -.-)

  • 写回答

2条回答 默认 最新

  • douyang5943 2014-08-15 14:49
    关注

    Basic PHP: '-quoted strings do NOT interpolate variables:

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

    Your code is trying to write your file out to a directory whose name is literally $, r, o, etc...

    Use "-quoted strings instead.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集