【问题标题】:Php file_put_contents with multiple files具有多个文件的php file_put_contents
【发布时间】:2015-07-10 10:24:08
【问题描述】:

我正在使用file_put_contents 创建信息并将其添加到 json 文件中。这可以成功,但是我需要创建两个具有不同名称的文件(title.jsondates.json) - 这可能吗?

我需要这样做的原因是因为我使用的是 twitter typeahead,它似乎只适用于单独的 json 文件。

它适用于单个文件,即;

file_put_contents(URL . '/title.json', json_encode($data));

但不是这样;

file_put_contents(URL . '/title.json', '/dates.json', json_encode($data));

我收到以下错误消息;

警告:file_put_contents() 期望参数 3 很长,字符串 在第 23 行的 C:\xampp\htdocs... 中给出

$sql = ("SELECT DISTINCT pub_id, title, place_name, party_name, publication_date FROM vw_ft_search");

$data = array();

while($row = $result->fetch_assoc())
{
    $data[] = array('title' => utf8_encode($row['title']),
                    'pub_id' => utf8_encode($row['pub_id']),
                    'place_name' => utf8_encode($row['place_name']),
                    'party_name' => utf8_decode($row['party_name']),
                    'publication_date'  => $row['publication_date']);
}

file_put_contents(URL . '/title.json','/dates.json', json_encode($data)); //line 23

我可能错过了一些非常简单的事情,感谢任何建议。

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    file_put_contents 只接受一个文件。使用循环插入所有文件 ->

    $files = array('/title.json', '/dates.json');
    

    然后遍历 $files:

    foreach($files as $file)
    {
        file_put_contents(URL.$file, json_encode($data));
    }
    

    【讨论】:

    • 谢谢@SidiaStudios 我尝试了你的建议但是现在我收到了错误Warning: file_put_contents(/dates.json): failed to open stream: Permission denied in C:\xampp\htdocs\... on line 27
    • 您无权写入 /dates.json(这将是服务器基本文件夹 -> dates.json)也许您的意思是 URL.'/dates.json' 也在那里?
    • 是的,完美,我必须输入 $files = array(URL . '/title.json', URL . '/dates.json'); 才能让它工作 - 谢谢!
    猜你喜欢
    • 2011-07-23
    • 2023-03-05
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多