[英]PHP read txt file with specific format
我需要一些有关 txt 文件阅读器的帮助。 有一个基于以下格式的文件:
{
id 0001
1 00000 1 10
2 00000 1 0
3 00000 1 0
4 00000 1 0
}
该文本文件包含各种这些块。 我想每行读取 id 和所有四个变量。 我最后有一个数组:
[
"0001_1" => ["var1"=>"1","var2"=>"00000","var3"=>"1","var4"=>"10"],
"0001_2" => ["var1"=>"2","var2"=>"00000","var3"=>"1","var4"=>"0"],
"0001_3" => ["var1"=>"3","var2"=>"00000","var3"=>"1","var4"=>"0"],
"0001_4" => ["var1"=>"4","var2"=>"00000","var3"=>"1","var4"=>"0"]
]
最后我想在表格中显示这些数据。 因此,如果您有更好的想法,如何将此文本文件块转换为表格,请告诉我:D
我的第一次尝试是将整个 txt 读取为字符串,然后读取所有“{”和“}”之间的内容以保存并将其从字符串中删除,然后继续从字符串中读取我的分隔符。
然后我在考虑二维数组,也许 Stackoverflow 的某个人知道更好的方法。
public function readFile(){
$source = file_get_contents(storage_path().'\app\public\file.txt',"r");
$found = $this->get_string_between($source,"{","}");
$source = str_replace($found,"",$source);
}
public function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
谢谢。
这种方法使用 preg_splits。 将文件拆分为行,并拆分每一行。 您可以将 $in 换成 file_get_contents() 调用。
<?php
$in =<<<IN
{
id 0001
1 00000 1 10
2 00000 1 0
3 00000 1 0
4 00000 1 0
}
IN;
$lines = preg_split('/\R/', $in);
$lines = array_map('trim', $lines);
$lines = array_map(function($v) { return preg_split('/\s+/', $v); }, $lines);
$lines = array_filter($lines, function($v) { return count($v) == 4; });
echo '<table>', "\n";
foreach($lines as $line) {
echo '<tr><td>', join('</td><td>', $line), '</td></tr>', "\n";
}
echo '</table>', "\n";
Output:
<table>
<tr><td>1</td><td>00000</td><td>1</td><td>10</td></tr>
<tr><td>2</td><td>00000</td><td>1</td><td>0</td></tr>
<tr><td>3</td><td>00000</td><td>1</td><td>0</td></tr>
<tr><td>4</td><td>00000</td><td>1</td><td>0</td></tr>
</table>
如果单元格顺序错误,您可以将 echo/implode 线换成具有正确占位符的 printf。
像这样的东西将为具有这种结构的所有匹配行完成这项工作:
<?php
$handle = fopen("./2.txt", "r");
if (!$handle) {
echo "Failed to read file";
exit(1);
}
$arrData = array();
$counter = 1;
while (($line = fgets($handle)) !== false) {
preg_match('/^\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+$/', $line, $matches);
if(count($matches) == 5) {
$key = '0001_' . $counter;
$counter++;
$arrData[$key] = array(
'var1' => $matches[1],
'var2' => $matches[2],
'var3' => $matches[3],
'var4' => $matches[4]
);
}
}
fclose($handle);
echo json_encode($arrData, JSON_PRETTY_PRINT);
echo "\n";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.