2014-08-27 69 views
0

我知道PHP的纯粹基础知识,而且我需要帮助将文本转换为.txt文件中的变量。从.txt文件获取PHP变量并丢弃字符

.txt文件中的文本(可以称之为“info.txt”)是在一行如下:

Robert | 21 | male | japanesse | 

所以我需要的是将信息转换变量如下:

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

请注意,我想放弃'|'每个数据之间。

我怎么能使用PHP?使用数组?怎么样?

+0

当使用'爆炸()'为你的答案建议,这将可能是最好使用'爆炸( “|” ...'而不是'explode(“|”...'所以你的字符串不会有多余的空格。如果字符串和分隔符之间的空格数目不一致,可能需要更复杂一点。 – 2014-08-27 16:44:24

回答

1

您可以使用PHP的file_get_contents() & explode()功能

$data = file_get_contents('info.txt'); 
$parsedData = explode("|", $data); 
var_dump($parsedData); 
2
<?php 
$file_content = file_get_contents($fileName); 
list($name, $age, $sex, $nationality) = explode("|", $file_content); 
echo "Hello ". $name; 

使用爆炸阵列中的获取信息。

0

您可以使用explode函数在PHP中“爆炸”一个字符串。您也可以使用file_get_contents来获取文件的内容。假设文件的格式始终一致,您可以将explodelist结合,直接指定给您的变量。

例如

<?php 

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

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

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

该读取文件 “file.txt” 的内容到一个数组,然后第一行的内容分配给该变量$name$age$sex$nationality

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]; 


阐释

  1. 首先加载使用 file_get_contents()功能info.txt内容在一个变量:

    $content = file_get_contents('info.txt'); 
    
  2. 其次,打破了内容转换成基于使用的|字符小件explode()功能。破碎的比特将被存储在一个数组中。

    $info = explode('|', $content); 
    
  3. 现在从步骤2使用如在其他的答案中示出的功能list()分配阵列中的每个值,以一个可变

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

    可以做在更短的方式这一步!


超短,为了好玩一行代码

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