使用简单的dom解析器通过特定的属性查找元素


Use simple dom parser to find an element by a specific attribute?

我有一个简单的dom解析器在工作,但我找不到任何文档或示例来通过属性的特定值获取元素。

我在一个页面上有几个表,但只有一个具有这些特定值的属性

<table cellpadding="2" cellspacing="1" bgcolor="#A0A0A0">

如何用这些值回显整个html表。

我所拥有的:

<?php include('simple_html_dom.php');
$url = htmlspecialchars($_GET["newURL"]);
$html = file_get_html ( $url );
echo $url;
foreach ( $html->find ( 'table' ) as $element ) {
    echo $element . PHP_EOL;
    flush ();
}
?>

你是否足够懒,阅读手册

Magic attributes部分

// Example
$html = str_get_html("<div>foo <b>bar</b></div>"); 
$e = $html->find("div", 0);
echo $e->tag; // Returns: " div"
echo $e->outertext; // Returns: " <div>foo <b>bar</b></div>"
echo $e->innertext; // Returns: " foo <b>bar</b>"
echo $e->plaintext; // Returns: " foo bar"

因此,在您的代码中,您可以使用echo $element->outertext;

将代码更改为

<?php
  if ( $table = $html->find( "table" ) ) {
    foreach( $table as $element ) {
      echo $element->outertext.PHP_EOL;
    }
  }
?>