Search code examples
phpjsonechomime-typesfwrite

Add content header to fwrite / fopen / fclose process


I'm writing to a .json file and I need to include headers so I can access it without problems. The headers I need to add to the index.php file :

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

The snippet of code that creates the .json file is:

public function saveCalendarAsFile() {
    $file2 = fopen("{$this->name}.txt", 'w');
    fwrite($file2, json_encode($this->events));
    fclose($file2);
}    

public function saveCalendarAsFile() {
    $file2 = fopen("{$this->name}.json", 'w');
    fwrite($file2, json_encode($this->events));
    fclose($file2);
}

No matter where I place the header (before line 1, 2 or 3, as this post suggests) it doesn't change the HTTP response of the external file (currently it's listed as text/plain).

The php file has those same headers in the document but according to multiple posts out there it needs to come before the "echo" statement. Since my code doesn't use an echo statement (as I'm writing to an external file) there must be another place to put the headers so it'll affect the .json file. Thanks in advance.

enter image description here


Solution

  • There is no need to set header while saving the target file on the server, but, if you want to be able to access that file (cross-domain) then you need to set Access-Control-Allow-Origin (exactly when you request that file from server).

    In Your case: you saved json file {$this->name}.json on your sever, if you want to receive that file and set (Access-Control-Allow-Origin) then you need to read that file using PHP and then set header for example:

    consider the file name is: myjson.json then you must not request that file directly, use php to read the file and then output it:

    jsonnreador.php
    <?php
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *');
    echo file_get_contents('myjson.json');
    ?>