How to Read a File Into an Array With PHP

PHP is a high-level scripting language often used on Web servers, although you can also use it as a command line language. You can use PHP to open a text file and read the contents of that file into an array. The PHP \"explode\" function is the function that will actually place the contents of the file into the array. The \"explode\" function returns an array of strings separated by a delimiter. The file is processed line by line using the \"fgets\" function.

Things You'll Need

  • Text editor
Show More

Instructions

    • 1

      Open a blank text document in any text editor.

    • 2

      Type the line:<br /><br /> <?PHP<br /><br />to start the PHP script.

    • 3

      Type the following line to create open the text file as read only:<br /><br />$fhandle = fopen(\"file.txt\", \"r\");

    • 4

      Type the following line to start the loop so the file can be read one line at a time:<br /><br />while (!feof($fhandle) ) {

    • 5

      Type the following line to input the file line by line:<br /><br />$text_line = fgets($fhandle);

    • 6

      Type the following line to place each separate word into the array:<br /><br />$words = explode(' ', $text_line)<br />GO<br /><br />In this example the delimiter for the \"explode\" function is a space (\" \") and the string is each word in the line of text.

    • 7

      Close the \"while\" loop, the file and the PHP script with the following three lines:<br /><br />}<br />fclose($file_handle)<br />GO<br />?>

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured