使用PHP简单HTML解析器查找前面的元素
我有一些HTML的设置如下(虽然可能会有所不同!):使用PHP简单HTML解析器查找前面的元素,php,Php,我有一些HTML的设置如下(虽然可能会有所不同!): 更新: 我在文档中发现可以使用prev_sibling(),所以我尝试了$table_title=$html->find('div[class=product table]table')->prev_sibling('h4')但似乎无法使其正常工作。我简化了示例,希望能够显示您的情况。之后,它确实假设标记紧跟在标记之前。但是它使用您找到的表标记的prev\u sibling() require_once 'simple_html_dom.p
更新:
我在文档中发现可以使用
prev_sibling()
,所以我尝试了$table_title=$html->find('div[class=product table]table')->prev_sibling('h4')代码>但似乎无法使其正常工作。我简化了示例,希望能够显示您的情况。之后,它确实假设
标记紧跟在
标记之前。但是它使用您找到的表标记的prev\u sibling()
require_once 'simple_html_dom.php';
$source = "<html>
<body>
<div class='product-table'>
<table>t1</table>
<h4>Content</h4>
<table>t2</table>
</div>
</body>
</html>";
$html = str_get_html($source);
$table_rows = $html->find('div[class=product-table] table');
foreach ($table_rows as $table){
$prev = $table->prev_sibling();
if ( !empty($prev) && $prev->tag == "h4") {
echo "h4=".(string)$prev->innertext().PHP_EOL;
}
echo "content=".(string)$table.PHP_EOL;
}
require_once'simple_html_dom.php';
$source=”
t1
内容
t2
";
$html=str_get_html($source);
$table_rows=$html->find('div[class=product table]table');
foreach($table\u行为$table){
$prev=$table->prev_sibling();
如果(!empty($prev)&&$prev->tag==“h4”){
echo“h4=”(字符串)$prev->innertext().PHP\u EOL;
}
echo“content=”(字符串)$table.PHP\u EOL;
}
回声
content=<table>t1</table>
h4=Content
content=<table>t2</table>
content=t1
h4=含量
内容=t2
如果您的代码是统一的,那么搜索“”可能会更容易。
require_once 'simple_html_dom.php';
$source = "<html>
<body>
<div class='product-table'>
<table>t1</table>
<h4>Content</h4>
<table>t2</table>
</div>
</body>
</html>";
$html = str_get_html($source);
$table_rows = $html->find('div[class=product-table] table');
foreach ($table_rows as $table){
$prev = $table->prev_sibling();
if ( !empty($prev) && $prev->tag == "h4") {
echo "h4=".(string)$prev->innertext().PHP_EOL;
}
echo "content=".(string)$table.PHP_EOL;
}
content=<table>t1</table>
h4=Content
content=<table>t2</table>