将两个文本文件与PHP结合使用 - ForEach循环

时间:2014-02-08 05:27:13

标签: php foreach

我完全不知道从哪里开始,但我需要在文件A中提供一个关键字列表,然后在列表B中提供相同的列表。

对于这些文件太多,我想在文件B的一个foreach行中附加行

例如:

文件A:
一号线
2号线
第3行

档案B:
test1的
TEST2
test3

输出到combined.txt文件:

line1test1
line2test1
line3test1
line1test2 ......等等

如果你能提供我要研究的脚本部分,一个示例脚本,甚至是一种工作方式。我将不胜感激。

根据请求,这是我的示例代码:

<?php

$file1 = 'keywords.txt';
$file2 = 'topics.txt';
$combined = 'combined.txt';

$keywords = fopen("keywords.txt", "rb");
$topics = fopen("topics.txt", "rb");
$front = explode($topics);
$back = explode($topics);

while (!feof($keywords) ) {

file_put_contents($combined, . $front ."". $back . "\n");

fclose($keywords & $topics);
}
?>

2 个答案:

答案 0 :(得分:1)

$f1 = explode("\n",file_get_contents("fileA.txt"));
$f2 = explode("\n",file_get_contents("fileB.txt"));
foreach ($f1 as $key => $value) {
    $f3[] = $value.$f2[$key];
}
file_put_contents("fileC.txt", implode("\n",$f3));

答案 1 :(得分:1)

希望这会有所帮助。整个代码中都有注释,我希望能够充分解释我正在做什么。

<?php

// Open keywords file for reading
$keywords_file = 'keywords.txt';
$keywords_fh = fopen($keywords_file, 'r');

// Get line by line from keywords file, push into $keywords array
// Make sure to trim each line from fgets, to strip off \n at end.
$keywords = array();
while ($line = trim(fgets($keywords_fh))) {
  array_push($keywords, $line);
}
fclose($keywords_fh);

// Open topics file for reading
$topics_file = 'topics.txt';
$topics_fh = fopen($topics_file, 'r');

// Get line by line from topics file, push into $topics array
// Make sure to trim each line from fgets, to strip off \n at end.
$topics = array();
while ($line = trim(fgets($topics_fh))) {
  array_push($topics, $line);
}
fclose($topics_fh);

// Open combined file for writing
$combined_file = 'combined.txt';
$combined_fh = fopen($combined_file, 'w');

// Iterate through each keyword.
// For each iteration, iterate through each topic.
// Write the concatenation of keyword and topic to file.
foreach ($keywords as $keyword) {
  foreach ($topics as $topic) {
    fwrite($combined_fh, "$keyword$topic\n");
  }
}

fclose($combined_fh);

以下是我使用的一些关键功能的PHP文档链接: