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;
DB_HOST=localhost
DB_NAME=demo_database
DB_USER=root
DB_PASSWORD=dbpswd15

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);
        }
    }
    fclose($fp);

    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");
Output:
Array
(
    [db_host] => localhost
    [db_name] => demo_database
    [db_user] => root
    [db_password] => dbpswd15
)


Hope that helps!

No comments:

Post a Comment

Please post any queries and comments here.