get a complete table with php domdocument and print it

独自空忆成欢 提交于 2019-12-24 10:16:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!