这听起来有点基本,但我不知道该怎么做, 我能够编写json文件,但我需要将它存储在特定的目录中。
$theColor = array('color' => 'red');
$fp = fopen('color.json', 'w');
fwrite($fp, json_encode($theColor));
fclose($fp);
现在我可以写这个,但文件出现在root上。我正在使用wordpress。我需要将它传输到特定文件夹或我的驱动器C:/
任何想法>
答案 0 :(得分:1)
替换以下行:
$fp = fopen('color.json', 'w');
与
$fp = fopen('/path/to/directory/color.json', 'w');
确保您对/path/to/directory/
拥有正确的权利。
修改强>
正如你的评论中所述。下载文件的代码。
$data = "/path/to/directory/color.json";
header("Content-Type: application/json");
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Disposition: attachment; filename="color.json"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($data));
readfile($data);
exit;
这应该会为您提供众所周知的弹出窗口。如果没有,请尝试首先将数据变量更改为file_get_contents("/path/to/directory/color.json")
或作为一项功能:
/**
* This method sets generates the headers for a file download and sends the file. PHP is exited after this function
*
* @param string $fileName The name of the file, as displayed in the download popup
* @param string $data The path to the file, or the contents of the file
* @param string $contentType The content type of the file
* @param bool $file Whether or not $data is a the path to a file, or the file data.<br />
* True means $data contains the path to the file<br />
* False when $data is a the data as a string
*
* @return void Exits PHP
*/
function outputForDownload($fileName, $data, $contentType, $file = true)
{
header("Content-Type: {$contentType}");
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Transfer-Encoding: binary');
if ($file === true) {
header('Content-Length: ' . filesize($data));
readfile($data);
} else {
header('Content-Length: ' . mb_strlen($data));
echo $data;
}
exit;
}