我想使用 php domddocument 从给定的 url 获取一个 id = 'myid' 的完整 html 表,并将其打印到我们的网页,我该怎么做?
我正在尝试使用以下代码获取表格,但无法获取 trs(表格行)和 tds(表格数据)和其他内部 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...
}
}
需要帮助。
我是 php domddocument 的新手。
非常感谢。
最佳答案
正如我所说,最好不要使用 getElementById。更好地分析我的测试样本;它有效
$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/