Jump to content

Extract values from text file


nathalie_vandv

Recommended Posts

I don't think there is such a function that exists. However it is rather simple to create. Here's what I've made:

<?php

function getVar($gVar)
{
    $txtFileContents = "a=1 b=2 c=3 d=4";

    // explode each variable in the file into an array on their own.
    $vars = explode(" ", $txtFileContents);
    /* produces an array like the following:
    array (
        [0] = "a=1"
        [1] = "b=2"
        ...
    } */

    // now we loop through each item in the $vars array.
    foreach($vars as $var)
    {
        // again we use explode and then we create two new variables
        // $name and $value.
        list($name, $value) = explode("=", $var);

        // we now create a new array which contains all
        // the variables in the file called $fileVars
        $fileVars[$name] = $value;
    }

    // now we check whether the variable that was passed to this
    // function exits in the $fileVars array and echo out the results
    if(array_key_exists($gVar, $fileVars))
    {
        echo $fileVars[$gVar];
    }
    else
    {
        echo $gVar . ' doesn\'t exist';
    }
}

getVar('c'); // get variable c -- returns "3"
// getVar('e'); // get variable e -- returns "e doesn't exist"

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.