2014-08-27 70 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"));