1

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];
        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).

  • eih, if this is an XML file, why dont you use an XML parser for that? – Gordon May 16 '11 at 17:26
  • Yeah I've been told that a couple times. I'm using this to learn how PHP works (I've never programmed in it). I will probably end up optimizing this later with a parser (when I learn what they are and how they work) –  May 16 '11 at 17:37
  • See http://stackoverflow.com/questions/188414/best-xml-parser-for-php/3616044#3616044 and http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662#3577662. On a sidenote, reading that file line by line is much easier done with a SplFileObject (there should be two code snippets in the duplicates I linked you on your previous question) – Gordon May 16 '11 at 17:43
  • Yeah I saw those and gave the manual a quick read, thanks :) –  May 16 '11 at 17:45

3 Answers3

4

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);
alexn
  • 57,867
  • 14
  • 111
  • 145
  • The line endings are what was causing it :) Thanks. Will accept in 7 minutes –  May 16 '11 at 17:14
0

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.

Ryan
  • 26,884
  • 9
  • 56
  • 83
0
$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.

Arjan
  • 9,784
  • 1
  • 31
  • 41