[英]Getting PHP variables from .txt file and discarding characters
我知道PHP的基本知識,我需要幫助將文本從.txt文件轉換為變量。
.txt文件中的文本(簡稱為“ info.txt”)如下所示:
Robert | 21 | male | japanesse |
所以我需要將信息轉換為變量,如下所示:
<?php
$name = 'Robert';
$age = '21';
$sex = 'male';
$nacionality = 'japanesse';
?>
請注意,我要舍棄“ |” 每個數據之間。
如何使用PHP做到這一點? 使用數組? 怎么樣?
<?php
$file_content = file_get_contents($fileName);
list($name, $age, $sex, $nationality) = explode("|", $file_content);
echo "Hello ". $name;
使用explode獲取數組中的信息。
您可以使用php的file_get_contents()和explode()函數
$data = file_get_contents('info.txt');
$parsedData = explode("|", $data);
var_dump($parsedData);
您可以使用explode
函數在PHP中“分解”字符串。 您也可以使用file_get_contents
來獲取文件的內容。 假設文件的格式始終一致,則可以將explode
與list
以直接分配給變量。
例如
<?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
//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];
首先使用file_get_contents()
函數將info.txt
中的內容加載到變量中:
$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"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.