得到一个完整的表与PHP domdocument并打印 [英] get a complete table with php domdocument and print it
本文介绍了得到一个完整的表与PHP domdocument并打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用php domddocument从给定的URL获取具有id ='myid'的完整html表,并将其打印到我们的网页上,我该怎么做?
我正在尝试使用以下代码来获取表,但无法获取trs(表行)和tds(表数据)以及其他内部html。
$ xml =新的DOMDocument();
@ $ xml-> loadHTMLFile($ url);
foreach($ xml-> getElementById('myid')as $ table)
{
//现在如何获取tr和td及其他元素?
//我正在获取其他元素,例如:-
$ links = $ table-> getElementsByTagName(’a’);
foreach($ links as $ innerAnchor)
{
//用锚标记做某事...
}
}
需要帮助。
我是php domddocument中的新手。 / p>
非常感谢。
解决方案
如我所言,最好不要使用getElementById。更好地分析我的测试样本;
$ html =< table ID ='myid'>< tr>< td> 1< / td< td> / td< / tr> tr< trd< td> 4< / td< td> 5< / td< / tr< tr> td> 7 / td> td> 8 / td> / tr>表。
$ xml =新的DOMDocument();
$ xml-> validateOnParse = true;
$ xml-> loadHTML($ html);
$ xpath =新的DOMXPath($ xml);
$ table = $ xpath-> query( // * [@ id ='myid'])-> item(0);
//用于打印整个html表,只需键入:print $ xml-> saveXML($ table);
$ rows = $ table-> getElementsByTagName( tr);
foreach($ rows as $ row){
$ cells = $ row-> getElementsByTagName(’td’);
foreach($ cells作为$ cell){
print $ cell-> nodeValue; //将单元格的内容打印为124578
}
}
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.
解决方案
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
}
}
这篇关于得到一个完整的表与PHP domdocument并打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文