【问题标题】:PHP Performing action on a variable line by linePHP逐行对变量执行操作
【发布时间】:2014-08-12 03:33:16
【问题描述】:

我有一个包含 html 代码的变量,我想对代码的每一行执行一个操作:

<?php

$html = file_get_contents('http://www.google.com/');

#how i would like it to be (not real commands)
/*
$line = 1
$currentline = readline($html,$line)
line++
where $html is the variable that we want to read a line from
$line is the line number
and $currentline the contents

so if $line is 1 we get that $currentline is <html> or whatever

after that i perform things on that line and continue reading each line untill i read all the lines

*/

?>

我希望你明白我的意思/需要。我对基于 Web 的编程非常陌生,所以我需要很多解释!

请不要使用您认为 PHP 程序员应该知道的技术术语,因为我可能不知道那是什么。

【问题讨论】:

  • file_get_html 应该用于 DOM 操作。你想做什么?为什么要逐行处理?
  • 我正在寻找一个库来做某事,现在我已经修复了它,因为我知道我可以使用不同的命令。

标签: php line-by-line


【解决方案1】:

您的问题类似于this one,尽管有人可能会争论答案对于初学者是否可以理解。这应该可以满足您的需求:

<?php

$html = file_get_contents('http://www.google.com/');
// Skipped: Error checks

// Split $html into lines
$lines = explode("\n", $html);

// Iterate over all lines
foreach($lines as $line) {
  // Process $line
}

// Or get the 5th line
$fifth_line = $lines[4];

// Or iterate using an index
for($line = 0; $line < count($lines); $line++) {
  $theline = $lines[$line];
}

【讨论】:

  • 非常有趣!我会看看它!我很高兴你发布了那个:) 但为什么会爆炸._。 foreach($lines as $line) 到底是什么?
  • 带有explode 的行给了我一个错误解析错误:语法错误,意外的T_VARIABLE
  • 函数explode确实存在..但给出了一个错误:)在命名这些命令@still_learning时一定有人玩得很开心
  • 这个例子对我有用,不应该有任何语法错误。您可以在php.net 找到有关explode 和foreach 的问题的答案,或者直接使用Google。
  • ahm @still_learning 我不知道为什么 foreach 不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
相关资源
最近更新 更多