Rasmus Nørskov
Rasmus Nørskov

Reputation: 474

PHP Look through file for specific line

I have a XML file looking like this

<table id="0">
</table>
<table id="1">
</table>
<table id="2">
</table>

I want to check if a table of id x exists

I have been trying this but does not work.

$file=fopen("config.xml","a+");
while (!feof($file))
  {
      if(fgets($file). "<br>" === '<table id="0">'){
        echo fgets($file). "<br>";
      }
  }
fclose($file);

Upvotes: 3

Views: 113

Answers (3)

Orbling
Orbling

Reputation: 20612

You can use the DOMDocument class, with XPath to find by ID, there is a getElementById() method, but it has issues.

// Setup sample data

$html =<<<EOT
<table id="0">
</table>
<table id="1">
</table>
<table id="2">
</table>
EOT;

$id = 3;

// Parse html
$doc = new DOMDocument();
$doc->loadHTML($html);

// Alternatively you can load from a file
// $doc->loadHTMLFile($filename);

// Find the ID
$xpath = new DOMXPath($doc);
$table = $xpath->query("//*[@id='" . $id . "']")->item(0);

echo "Found: " . ($table ? 'yes' : 'no');

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227310

You are opening the file with mode 'a+'. The 'a' means append, so it puts the pointer at the end of the file.

If you want to read the file, you probably want to start at the beginning, so use mode 'r' (or 'r+'). Check the manual for the different file modes: http://www.php.net/manual/en/function.fopen.php

Also, fgets($file). "<br>" === '<table id="0">' will never be true! You are appending <br> to the string, and then comparing it to <table id="0"> expecting it to match.

$file = fopen("config.xml", "r");
while (!feof($file)){
    $line = fgets($file);
    if($line === '<table id="0">'){
        echo $line. "<br>";
    }
}
fclose($file);

Upvotes: 1

Tomasz Kapłoński
Tomasz Kapłoński

Reputation: 1378

The easiest way to accomplish that is using PHP Simple HTML DOM class:

$html = file_get_html('file.xml');
$ret = $html->find('div[id=foo]'); 

[edit] As for the code that does not work... Please notice that the xml you pasted does not have
characters so this string comparison will return false. If you want to take in consideration new line you should rather write \n... However the solution above is better because you don't have to get very strictly formated input file.

Upvotes: 4

Related Questions