Search code examples
phputf-8fwritefputs

php 5.6.7 fwrite vs fputs utf-8 encoding


I have a xml data that is sent as a string in a url.

For example url?data=string

This is sent to another server that I do not have control over and they use fputs so I can not simply change to fwrite. I am trying to figure out how to make the fputs work so that I can give them the fix. My test environment is using php 5.6.7.

In the string is the character á (alt+0225).

Using this code the character is still á when I view the file in notepad++.

 $datafile = fopen("datafile.txt", "a");
 foreach (getallheaders() as $name => $value){
      $y = "$name: $value\n";
      fwrite($datafile,$y);
 }
 fclose($datafile);

Using this code the á is turn into something else when viewed using notepad++.

 $datafile_fputs = fopen("datafile_fputs.txt", "a");
 foreach (getallheaders() as $name => $value) {
      $y = "$name: $value\n"; 
      fputs($datafilefputs,$y);
 }
 fclose($datafile_fputs);

I have attempted this as found here on stackoverflow and the character is still displayed incorrectly.

 $file = "datafile_fputs";
 $datafile_fputs = fopen($file, "a");
 foreach (getallheaders() as $name => $value) {
      $y = "$name: $value\n"; 
      $file = "\xEF\xBB\xBF".$file;
      fputs($datafile_fputs,$y);
 }
 fclose($datafile_fputs);

Anyone know why fputs acts differently and how to fix it?


Solution

  • This is the only solution that I could come up with. When running the below code into a file, using getallheaders, the fputs of the $_REQUEST['data'] worked. I assume the header of the file is set to the BOM of utf-8 and therefore everything that is entered after it is properly encoded.

     $file = "datafile_fputs";
     $datafile_fputs = fopen($file, "a");
          foreach (getallheaders() as $name => $value) {
               $y = "\xEF\xBB\xBF"; 
               $y .= "$name: $value\n";
               fputs($datafile_fputs,$y);
      }
      fputs($datafile_fputs,$_REQUEST['data']);
      fclose($datafile_fputs);