我知道PHP的纯粹基础知识,我需要帮助将文本转换为.txt文件中的变量。
.txt文件中的文本(我们称之为'info.txt')在一行中,如下所示:
Robert | 21 | male | japanesse |
所以我需要的是将变量中的信息转换成如下:
<?php
$name = 'Robert';
$age = '21';
$sex = 'male';
$nacionality = 'japanesse';
?>
注意我要丢弃'|'每个数据之间。
我怎么能用PHP做到这一点?使用数组?怎么样?
答案 0 :(得分:2)
<?php
$file_content = file_get_contents($fileName);
list($name, $age, $sex, $nationality) = explode("|", $file_content);
echo "Hello ". $name;
使用explode获取数组中的信息。
答案 1 :(得分:1)
你可以使用php的file_get_contents()&amp; explode()函数
$data = file_get_contents('info.txt');
$parsedData = explode("|", $data);
var_dump($parsedData);
答案 2 :(得分:0)
你可以&#34;爆炸&#34; PHP中使用explode
函数的字符串。您还可以使用file_get_contents
来获取文件的内容。假设文件的格式始终一致,您可以将explode
与list
结合使用,直接分配给您的变量。
例如
<?php
$string = file_get_contents("file.txt");
$lines = explode("\n", $string);
list($name, $age, $sex, $nationality) = explode("|", $lines[0]);
这将读取&#34; file.txt&#34;的内容。到数组中,然后将第一行的内容分配给变量$name
,$age
,$sex
,$nationality
答案 3 :(得分:0)
//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];
首先使用。在info.txt
中加载变量中的内容
file_get_contents()
功能:
$content = file_get_contents('info.txt');
其次,使用explode()
函数根据|
字符将内容分解为小块。损坏的位将存储在一个数组中。
$info = explode('|', $content);
现在将数组中的每个值从步骤2分配给变量
$name = $info[0];
$age = $info[1];
$sex = $info[2];
$nationality = $info[3];
您可以使用list()
函数以更短的方式执行此步骤,如其他答案中所示!
<小时/> 超短,一行有趣的代码
list($name, $age, $sex, $nationality) = explode("|", file_get_contents("file.txt"));