简体   繁体   中英

Getting PHP variables from .txt file and discarding characters

I know the pure basics of PHP, and I need help converting text into variables from a .txt file.

The text inside the .txt file (lets call it 'info.txt') is in a single line as follows:

Robert | 21 | male | japanesse | 

So what I need is to convert the information in variables as follows:

<?php
   $name = 'Robert';
   $age = '21';
   $sex = 'male';
   $nacionality = 'japanesse';
?>

Note that I want to discard the '|' between every data.

How could I do that using PHP? Using arrays? How?

<?php
$file_content = file_get_contents($fileName);
list($name, $age, $sex, $nationality) = explode("|", $file_content);
echo "Hello ". $name;

Use explode to get information in an array.

You can use php's file_get_contents() & explode() functions

$data = file_get_contents('info.txt');
$parsedData = explode("|", $data);
var_dump($parsedData);

You can "explode" a string in PHP using the explode function. You can also use file_get_contents to get the contents of a file. Assuming that the format of the file is always consistent, you can couple explode with list to assign directly to your variables.

For example

<?php

$string = file_get_contents("file.txt");

$lines = explode("\n", $string);

list($name, $age, $sex, $nationality) = explode("|", $lines[0]);

This reads the contents of "file.txt" into an array, and then assigns the first line's contents to the variables $name , $age , $sex , $nationality

Code

//Step 1
$content = file_get_contents('info.txt');

//Step 2
$info = explode('|', $content);

//Step 3
$name =         $info[0];
$age  =         $info[1];
$sex  =         $info[2];
$nationality =  $info[3];


Explaination

  1. First load the contents in info.txt in a variable using the file_get_contents() function:

     $content = file_get_contents('info.txt'); 
  2. Second, break up the content into little pieces based on the | character using the explode() function. The broken bits will be stored in an array.

     $info = explode('|', $content); 
  3. Now assign each value in the array from step 2 to a variable

     $name = $info[0]; $age = $info[1]; $sex = $info[2]; $nationality = $info[3]; 

    you can do this step in a shorter way using the list() function as shown in the other answers!


Ultra short, one line code for fun

 list($name, $age, $sex, $nationality) = explode("|", file_get_contents("file.txt")); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM