php 使用PHP将文本文件转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24906108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:32:07  来源:igfitidea点击:

Use PHP to convert text file into array

phpexplode

提问by Malignus

I have a text file herewhich I need to be able to convert into rows to extract the second, third, fourth, and fifth values from.

我在这里有一个文本文件,我需要能够将其转换为行以从中提取第二、第三、第四和第五个值。

The first 7 values of each row are tab delimited, then there is a newline, then the final three values are tab delimited.

每行的前 7 个值以制表符分隔,然后是换行符,最后三个值以制表符分隔。

I removed the interrupting newlines so that each row is fully tab delimited.

我删除了中断的换行符,以便每一行都完全由制表符分隔。

<?php

$file="140724.txt";

$fopen = fopen($file, "r");

$fread = fread($fopen,filesize("$file"));

fclose($fopen);

$remove = "\n";

split = explode($remove, $fread);

foreach ($split as $string)
{
echo "$string<br><br>";
}

?>

Which produces this.

这产生了这个

I'm not sure where to progress from this point. I'm teaching myself PHP and am still quite new to it, so I don't even know if where I've started from is a good place. My instinct is to write the previous output to a new textfile, then create another block of code similar to the first but exploding based on tabs, this time.

我不知道从这一点上取得进展。我正在自学 PHP 并且对它仍然很陌生,所以我什至不知道我从哪里开始是一个好地方。我的直觉是将之前的输出写入一个新的文本文件,然后创建另一个类似于第一个但基于选项卡爆炸的代码块,这一次。

Help?

帮助?

回答by Artur K?dzior

You can process this file in one go like this:

你可以像这样一次性处理这个文件:

<?php
    $file="140724.txt";

    $fopen = fopen($file, r);

    $fread = fread($fopen,filesize($file));

    fclose($fopen);

    $remove = "\n";

    $split = explode($remove, $fread);

    $array[] = null;
    $tab = "\t";

    foreach ($split as $string)
    {
        $row = explode($tab, $string);
        array_push($array,$row);
    }
    echo "<pre>";
    print_r($array);
    echo "</pre>";
?>

The result will be a jagged array:

结果将是一个锯齿状的数组:

enter image description here

在此处输入图片说明

You will need to clean up the 1st and the last element.

您需要清理第一个和最后一个元素。

回答by feeela

That is structured data, delimited by tabs. You can use fgetcsv()to read that data into an array. For an example see the PHP documentation.

那是结构化数据,由制表符分隔。您可以use fgetcsv()将该数据读入数组。有关示例,请参阅 PHP 文档。

回答by user5707714

<?php
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
    $text[] = fgets($myfile);
}
fclose($myfile);
print_r($text);
?>

回答by Shivam Sharma

There is another answer herewhich converts file/raw strings into an associative array. It is really very handy in such cases.

这里有另一个答案它将文件/原始字符串转换为关联数组。在这种情况下它真的非常方便。

function tab_to_array($src='', $delimiter=',', $is_file = true)
{
    if($is_file && (!file_exists($src) || !is_readable($src)))
        return FALSE;

    $header = NULL;
    $data = array();

    if($is_file){
        if (($handle = fopen($src, 'r')) !== FALSE)
        {
            while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
            {
                if(!$header)
                    $header = $row;
                else
                    $data[] = array_combine($header, $row);
            }
            fclose($handle);
        }
    }
    else{
        $strArr = explode("\n",$src);
        foreach($strArr as $dataRow){
            if($row = explode($delimiter,$dataRow))
            {
                if(!$header)
                    $header = $row;
                else
                    $data[] = array_combine($header, $row);
            }
        }
    }

    return $data;
}
/**
 * Example for file
 */
print_r(tab_to_array('example.csv'));
/**
 * Example for raw string
 */
$str = "name    number
Lorem   11
ipsum   22";
print_r(tab_to_array($str, "\t", false));