[英]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. 我知道PHP的基本知识,我需要帮助将文本从.txt文件转换为变量。
The text inside the .txt file (lets call it 'info.txt') is in a single line as follows: .txt文件中的文本(简称为“ info.txt”)如下所示:
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? 如何使用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. 使用explode获取数组中的信息。
You can use php's file_get_contents() & explode() functions 您可以使用php的file_get_contents()和explode()函数
$data = file_get_contents('info.txt');
$parsedData = explode("|", $data);
var_dump($parsedData);
You can "explode" a string in PHP using the explode
function. 您可以使用explode
函数在PHP中“分解”字符串。 You can also use file_get_contents
to get the contents of a file. 您也可以使用file_get_contents
来获取文件的内容。 Assuming that the format of the file is always consistent, you can couple explode
with list
to assign directly to your variables. 假设文件的格式始终一致,则可以将explode
与list
以直接分配给变量。
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
这会将“ file.txt”的内容读入数组,然后将第一行的内容分配给变量$name
, $age
, $sex
, $nationality
//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];
First load the contents in info.txt
in a variable using the file_get_contents()
function: 首先使用file_get_contents()
函数将info.txt
中的内容加载到变量中:
$content = file_get_contents('info.txt');
Second, break up the content into little pieces based on the |
其次,根据|
将内容分为几部分 character using the explode()
function. 使用explode()
函数的字符。 The broken bits will be stored in an array. 损坏的位将存储在数组中。
$info = explode('|', $content);
Now assign each value in the array from step 2 to a variable 现在将步骤2中数组中的每个值分配给一个变量
$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! 您可以使用list()
函数以更短的方式执行此步骤,如其他答案所示!
list($name, $age, $sex, $nationality) = explode("|", file_get_contents("file.txt"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.