我是PHP/JavaScript新手,不知道如何编写代码来使用PHP/JavaScript从文本文件中提取数据。
数据:
-bash-4.1$ cat Data/data/XYZ.txt
XYZ - - -
Day1 12 28 MCS
Day2 15 30 PCS
Day3 18 28 LH
Day4 11 26 SUN
Day5 20 34 RA
Day6 16 26 PCS
Day7 6 15 FO
-bash-4.1$我想要有4个应该有值的变量:
v1=Day1 v2=12 v3=28 and v4=MCS**我所做的只是从文件中提取了第一个字符串,代码如下所示。
<?php
echo '<p>Hello World</p>';
$myfile = fopen("Data/data/XYZ.txt", "r") or die("Unable to open file!");
$line=fgets($myfile);
echo $line;
fclose($myfile);?>发布于 2018-12-18 13:01:04
尝尝这个。产出:
v1=Day1 v2=12 v3=28 v4=MCS
v1=Day2 v2=15 v3=30 v4=PCS
v1=Day3 v2=18 v3=28 v4=LH
v1=Day4 v2=11 v3=26 v4=SUN
v1=Day5 v2=20 v3=34 v4=RA
v1=Day6 v2=16 v3=26 v4=PCS
v1=Day7 v2=6 v3=15 v4=FO关于一步一步的解释,请参见注释:
<?php
// Input specified as string for the sake of this demo.
$inputData = <<<EOT
XYZ - - -
Day1 12 28 MCS
Day2 15 30 PCS
Day3 18 28 LH
Day4 11 26 SUN
Day5 20 34 RA
Day6 16 26 PCS
Day7 6 15 FO
EOT;
// Split string on EOL character, into array.
$input = explode(PHP_EOL, $inputData);
// Or, if you're reading from a file, comment everything above and uncomment the following line:
// $input = file('Data/data/XYZ.txt');
// $input is now an array, and allows us to iterate over it using foreach.
// $rowIndex will hold the array index, $line will hold a single line from the input.
foreach ($input as $rowIndex => $line)
{
// Skip header.
if ($rowIndex == 0)
continue;
// Trim any unwanted leading whitespace, so the resulting array starts with a usable value.
// preg_split() will split the line on whitespace, and return an array of all column values.
$cols = preg_split('/[\s]+/', trim($line));
// You can now read out the array of column values however you see fit.
$v1 = $cols[0];
$v2 = $cols[1];
$v3 = $cols[2];
$v4 = $cols[3];
echo "v1=$v1 v2=$v2 v3=$v3 v4=$v4<br>\n";
}发布于 2018-12-18 12:51:53
步骤:
1)可以使用fopen打开文件,并以字符串的形式获取内容。
2)用新的行字符拆分(爆炸())得到的字符串。
3)现在循环遍历我们从步骤2获得的数组。在每次迭代中,您将从文件中得到一行。
代码:
<?php
// Open the file
$filename = 'xyz.txt';
$fp = fopen($filename, 'r');
// Add each line to an array
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
}
if (! empty($array)) {
foreach ($array as $line) {
$cols = preg_split('/[\s]+/', trim($line));
echo '<pre>';print_r($cols);echo '</pre>';
}
}
?>响应:
Array
(
[0] => Day1
[1] => 12
[2] => 28
[3] => MCS
)
Array
(
[0] => Day2
[1] => 15
[2] => 30
[3] => PCS
)
Array
(
[0] => Day3
[1] => 18
[2] => 28
[3] => LH
)
Array
(
[0] => Day4
[1] => 11
[2] => 26
[3] => SUN
)
Array
(
[0] => Day5
[1] => 20
[2] => 34
[3] => RA
)
Array
(
[0] => Day6
[1] => 16
[2] => 26
[3] => PCS
)
Array
(
[0] => Day7
[1] => 6
[2] => 15
[3] => FO
)https://stackoverflow.com/questions/53833322
复制相似问题