开发者

Looking for a line in a file PHP

This loop doesn't seem to be finding the lines I want it to (it's not finding anything at all actually).

$file_lines = file("rss.xml");
$max_lines = count($file_lines);
$id = $_POST['id_number'];
$start_string = " <!--".$id."-->";
$start_line;
$end_string = "<!--end of item ".$id."-->";
$end_line;

for ($i = 0; $i < $max_lines; $i++) {
        $temp_line = $file_lines[$i];
开发者_StackOverflow中文版        if ($temp_line == $start_string) {
                $start_line = $i;
                echo "found start";
        }

        if ($temp_line == $end_string) {
                $end_line = $i;
                echo "found end";
        }
}

It's supposed to be going through a file line-by-line and looking to see if it matches a preset string. If it does, it is supposed to set a variable to the position of the line (the counter $i).


An option is to use array_search:

$index = array_search($start_string, $file_lines);

$index will be the key of your found element, if any.

You can check if you have got a result by checking for false:

if($index !== FALSE) {
    // We have a result, act accordingly. You can get the matched line:
    echo "Line found: " . $file_lines[$index];
}

As mentioned below, file does not trim line endings. You can use the FILE_IGNORE_NEW_LINES flag to skip this:

$lines = file("rss.xml", FILE_IGNORE_NEW_LINES);


Just a shot in the dark, but the input file may contain end-of-line characters (e.g. \n), which may throw off your comparison using ==. Try using a function such as strpos.


$start_string = " <!--".$id."-->";

You have a space before the < in that line. I don't know if that's supposed to be there, but it could easily cause unexpected results if it's not in the input file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜