2015-06-11 28 views
-1

我有以下传入txt文件:循环在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; 
} 

我想有一个循环读取变量中的第一个标题存储,然后读取详细信息,每次点击'I'时,它会将该行上传到MYSQL。

一旦它再次击中H,我该如何回到循环的顶部?

谢谢你从noobie。

+0

我这里看不到一个循环 – developerwjk

回答

0

我想有一个循环读取变量中的第一个标头存储然后阅读详细信息,每次它点击'我'它将该行上传到MYSQL。

解析文件有多种方法。

下面的方法利用的explode()为H和I

所以,你有一个“外循环”为H(H header1 yyyy I detailofheader1 I detailofheader1) - 来处理单独报头。

而我的一个“内循环”(header1 yyyy I detailofheader1 I detailofheader1) - 处理标题数据本身和细节。

SQL明智:

  • 我不知道你的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; 
    } 
} 
0

你的循环会是怎样读取文件的每一行,为$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 
    .... 
}