循环读取包含多个 headers 和 php 中的详细信息的 txt 文件

Loop for reading txt file with multiple headers and detail items in php

我有以下传入的 txt 文件:

H header1 yyyy
I detailofheader1
I detailofheader1
H header2 xxxx
I detailofheader2
I detailofheader2

以及以下代码:

$action = substr($line_of_text, 0, 1);
if (($action == 'H') )  {
//STORE IN VARIABLES ;
}
if (($action == 'I') )  {
//store in variables and upload header and detail variables to mysql;
}

我想先读取一个循环 header 存储在变量中,然后读取详细信息,每次它命中 'I' 时,它都会将该行上传到 MYSQL。

再次点击 H 后如何返回循环顶部?

来自新手的感谢。

I would like to have a loop read first header store in variable then read details and everytime it hits 'I' it uploads that line to MYSQL.

有多种方法可以解析您的文件。

以下方法对 H 和 I 使用 explode()

所以你有一个 "outer loop" 用于 H (H header1 yyyy I detailofheader1 I detailofheader1) - 处理个人 headers.

我 "inner loop" (header1 yyyy I detailofheader1 I detailofheader1) - 处理 header 数据本身和详细信息。

SQL-wise:

  • 我不知道您的 SQL 架构 - 只是猜测架构。
  • 我在哪里使用 echo $sql - 你可以执行查询。
  • 这是示例 SQL,正确转义以确保安全

无论如何,这里有一些可以玩的东西。希望这能让你开始......

<?php

// example data to work with
$string = 'H header1 yyyy I detailofheader1 I detailofheader1 H header2 xxxx I detailofheader2 I detailofheader2';

// later just
// $string = file("file.txt");

// get rid of the first H (to ease exploding / no empty first array item)
$string =  ltrim($string, 'H');

// explode string into array - by using H as char for the split
$headers = explode('H', $string);

foreach($headers as $idx => $line)
{
    $line = trim($line); // remove spaces at begin/end

    //echo 'Processing: [' . $idx . '] ' . $line . PHP_EOL;

    // second explode, this time using "I"
    $data = explode('I', $line);

    foreach($data as $dataIdx => $details)
    {
        $details = trim($details); // remove spaces at begin/end

        //echo '           ' . $details . PHP_EOL;

        // first dataIdx is the header data "header1 yyyy"
        if($dataIdx === 0) {
            // string contains a space, split
            $headerItems = explode(' ', $details);
            $headerNumber = trim($headerItems[0]); // header1
            $headerString = trim($headerItems[1]); // yyyy`

            // => insert the header

            $sql = "INSERT INTO table_headers (id, name) VALUES ('$headerNumber',' $headerString')";
            echo $sql . PHP_EOL;

            // we are done, skip to next element
            continue;
        } 

        // else its a "detailofheaderX"
        // so use details in the insert query

        $sql = "INSERT INTO table_data (header_id, detail) VALUES ('$headerNumber', '$details')";
        echo $sql . PHP_EOL;
    }
}

您的循环将读取文件的每一行,为 $line_of_text 提供一个值。两种方法:

$handle = fopen("/file/name.txt", "r");
while (!feof($handle)) {
    $line_of_text = fgets($handle);
    // do stuff with line of text
    ....
}
fclose($handle);

或者,我的首选方法:

$all_lines = file("/file/name.txt");
foreach ($all_lines as $line_of_text) {
    // do stuff with line of text
    ....
}