Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Look through file for specific line

Tags:

php

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);
like image 352
Rasmus Nørskov Avatar asked Nov 26 '25 02:11

Rasmus Nørskov


2 Answers

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.

like image 183
Tomasz Kapłoński Avatar answered Nov 28 '25 15:11

Tomasz Kapłoński


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');
like image 42
Orbling Avatar answered Nov 28 '25 15:11

Orbling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!