user2077308 user2077308 - 2 months ago 20
PHP Question

get value using DOM HTML

I want to get all the

td
of the ninth
table
element in an HTML page.

I started with this , but I dont know how to finish it :

define('GLPI_ROOT', '..');
$content = GLPI_ROOT . "/front/yourpage.html";
$dom = new DOMDocument();
@$dom->loadHTML($content);
$xpath = new DOMXPath($dom);

$attbs = $xpath->query("//table td");
foreach($attbs as $a) {
print $a->nodeValue;
}


And I have tried this one too, but it didn't work :

$dom = new DOMDocument();
$dom->loadHTMLFile("yourpage.html");
$tables = $dom->getElementsByTagName('table');
$table = $tables->item(8);

foreach ($table->childNodes as $td) {
if ($td->nodeName == 'td') {
echo $td->nodeValue, "\n";
echo "<script type=\"text/javascript\"> alert('".$td->nodeValue."');</script>";
}
}


I'm getting this error :

Warning: DOMDocument::loadHTMLFile(): htmlParseEntityRef: expecting ';' in yourpage.html, line: 33

Answer

Your first one doesn't work because you don't seem to be understanding how XPath works, but your second one is probably a better option.

That said, when has <td> ever been a first-level child of <table>? You could use getElementsByTagName again on the $table, that'd work quite well.

Comments