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);
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With