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"

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.