Thursday, 6 August 2015

How to read a file content and convert it into an array

If you have a config.txt file containing the following code;

Please use the below function to read the text file content into an array with key and values;
 * Function to read the file content and return into an array separating key = value;
 * @param $filepath The Document File path to read the file contents;
 * @return array Return the files content into array by separating each lines with '=' separated with first part as key (into lowercase) and second part key's as value.
function get_file_content_in_array($filepath)
    $fp = fopen($filepath, "r") or die("Please configure the forum database.");

    $lines = array();

    while (!feof($fp))
        $line = fgets($fp);

        //process line however you like
        $line = trim($line);

        // If line empty, do continue
        if (empty($line)) continue;

        // Split the line string with '=' operator into key and value;
        list($key, $value) = explode('=', $line);

        // check the empty key
        if (!empty($key)) {
            //add to array
            $lines[trim($key)] = trim($value);

    return $lines;

To read the file content, just call the above below script after including the above function.

// Read the file and content and convert it into an array
$config = get_file_content_in_array($filepath = "cofig.txt");
    [db_host] => localhost
    [db_name] => demo_database
    [db_user] => root
    [db_password] => dbpswd15

Hope that helps!