2017-05-30 41 views
1

這聽起來有點基本,但我不知道如何做到這一點, 我能寫json文件,但我需要它存儲在一個特定的目錄。在目錄上寫json php

   $theColor = array('color' => 'red'); 
       $fp = fopen('color.json', 'w'); 
       fwrite($fp, json_encode($theColor)); 
       fclose($fp); 

現在我可以寫這個,但文件出現在根。我正在使用wordpress。我需要把它轉移到一個特定的文件夾或我的驅動器C:/

任何想法>

回答

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; 
} 
+0

由於其工作。 您是否還知道如何在保存後下載該文件。假設文件是​​從服務器保存的,我將它下載到我的本地 –

+0

看我的編輯,我還包括我用它的功能 – Jelmergu