Home > OS >  PHP file reading
PHP file reading

Time:04-06

I have a txt file with name source.txt and has the following content.

Name = "john"
image = "/path"
email = "[email protected]"

and some other data

I read and echo all the content. But I want specific data and assign to the variable. if I need name. Then read the file and select john and assign to the variable

CodePudding user response:

Here an mini code example

test.txt :

Name = "john"
image = "/path"
email = "[email protected]"

exemple script

<?php
$data_array = array();
$data_array_2 = array();
$fp = @fopen("./test.txt", "r");
if ($fp) {
    while (($line = fgets($fp)) !== false) {
        array_push($data_array,explode("=",$line));
        list($key,$val) = explode("=",$line);
        $data_array_2[$key] = $val;
    }
}
fclose($fp);
echo "<pre>";
var_dump($data_array);
echo "</pre>";
echo "<pre>";
var_dump($data_array_2);
echo "</pre>";
?>

CodePudding user response:

You can use native function parse_ini_file to parse it like .ini file.

Example.

File test.txt:

Name = "john"
image = "/path"
email = "[email protected]"

Code (like .ini):

$ini_array = parse_ini_file("test.txt");
print_r($ini_array);

// Result
// Array
// (
//    [Name] => john
//    [image] => /path
//    [email] => [email protected]
// )

// Import variables into the current symbol table from an array
// Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).
extract($ini_array);
echo $Name; // john

Update.

File test2.txt:

name = "john" | image="/path"
name = "john2" | image="/path2"

Very simplified code (parse like raw file with lines):

function parse_raw_file($filepath) {
    
    $result = [];
    $file = file($filepath);
    
    if(count($file) > 0) {

        foreach($file as $k => $v) {

            $parts = explode("|", $v);
            
            foreach($parts as $part) {

                $value = explode("=", $part);
                $key = trim($value[0]);
                $result[$k][$key] = trim($value[1]);

            }

        }

    }

    return $result; 

}

$array = parse_raw_file("test2.txt");
print_r($array);

// Array
// (
//    [0] => Array
//        (
//            [name] => "john"
//            [image] => "/path"
//        )
//
//    [1] => Array
//        (
//            [name] => "john"
//            [image] => "/path2"
//        )
//
//)

// Assign variables 

foreach ($array as ["name" => $name, "image" => $image]) {
    echo "name: $name, image: $image\n";
}

// name: "john", image: "/path"
// name: "john", image: "/path2" 

  •  Tags:  
  • php
  • Related