问题
I would like to get a complete html table having id = 'myid' from a given url using php domddocument and print it to our web page, How can i do this ?
I am trying with below code to get table but i cant getting trs(table rows) and tds(table data) and other inner html.
$xml = new DOMDocument();
@$xml->loadHTMLFile($url);
foreach($xml->getElementById('myid') as $table)
{
// now how to get tr and td and other element ?
// i am getting other element like :-
$links = $table->getElementsByTagName('a');
foreach($links as $innerAnchor)
{
//doing something with anchor tag...
}
}
Need help.
I am new in php domddocument.
Thanks a lot.
回答1:
As I commented it's better not to use getElementById. Better analyze my test sample; it works
$html = "<table ID='myid'><tr><td>1</td><td>2</td></tr><tr><td>4</td><td>5</td></tr><tr><td>7</td><td>8</td></tr></table>";
$xml = new DOMDocument();
$xml->validateOnParse = true;
$xml->loadHTML($html);
$xpath = new DOMXPath($xml);
$table =$xpath->query("//*[@id='myid']")->item(0);
// for printing the whole html table just type: print $xml->saveXML($table);
$rows = $table->getElementsByTagName("tr");
foreach ($rows as $row) {
$cells = $row -> getElementsByTagName('td');
foreach ($cells as $cell) {
print $cell->nodeValue; // print cells' content as 124578
}
}
来源:https://stackoverflow.com/questions/7429136/get-a-complete-table-with-php-domdocument-and-print-it