How to Output Escape Characters to File in PHP

When you are writing to a file with PHP, you sometimes need to output special characters to the file. For example, if you want to insert a new line in a data file, you have to output a carriage-return character and a line-feed character to the file. Because these are not printable characters, you have to use special escape characters to represent them in the file. An escape character is a combination of the forward-slash character and a character abbreviation.

Instructions

    • 1

      Create a new PHP program file using an editor. For example, type:

      nano escapeout.php

    • 2

      Open a file in write mode. For example, type:

      <?php

      $fh = fopen("output.dat", "w");

      if (!$fh) die("Could not open output file!");

    • 3

      Create a variable to store the data you want to write to the file. Add the carriage-return escape character "\r" and the new-line escape character "\n" to the variable. For example, type:

      $output = "This is the output string for the file\r\n";

    • 4

      Write the data to the file and close the file. For example, type:

      fputs($fh, $output);

      fclose($fh);

      ?>

    • 5

      Exit the editor and save the file. Navigate to the file in a browser to run it and test the program's functionality.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured