从简单HTMLDOM-PHP中排除非需要的html
我正在使用HTML简单Dom解析器和PHP从网站获取标题、描述和图像。我面临的问题是我得到了我不想要的html,以及如何排除这些html标记。下面是解释 下面是一个正在解析的示例html结构从简单HTMLDOM-PHP中排除非需要的html,php,parsing,web-scraping,html-parsing,simple-html-dom,Php,Parsing,Web Scraping,Html Parsing,Simple Html Dom,我正在使用HTML简单Dom解析器和PHP从网站获取标题、描述和图像。我面临的问题是我得到了我不想要的html,以及如何排除这些html标记。下面是解释 下面是一个正在解析的示例html结构 <div id="product_description"> <p> Some text</p> <ul> <li>value 1</li> <li>value 2</li> <li>value 3&
<div id="product_description">
<p> Some text</p>
<ul>
<li>value 1</li>
<li>value 2</li>
<li>value 3</li>
</ul>
// the div I dont want
<div id="comments">
<h1> Some Text </h1>
</div>
</div>
一些文本
- 值1
- 价值2
- 价值3
//我不想要那个div
一些文本
我用下面的php脚本来解析
foreach($html->find('div#product_description') as $description)
{
echo $description->outertext ;
echo "<br>";
}
foreach($html->find('div#product_description')作为$description)
{
echo$description->outertext;
回声“
”;
}
上面的代码解析id为“product_description”的div中的所有内容。我想排除Id为“comments”的div。我尝试将其转换为字符串,然后使用substr排除最后一个字符,但这不起作用。不知道为什么。你知道我该怎么做吗?任何允许我从解析的html中排除div的方法都可以。谢谢您可以通过设置元素的
outertext=''
来删除不需要的元素:
$src=
outertext='';
打印$description->outertext;
}
好吧,我想我自己只要使用高级HTMLDOM库,它与简单的HTMLDOM完全兼容&通过使用它,您将获得更多的控制权。从解析的html中删除所需内容非常简单。例如
//to remove script tag
$scripts = $description->find('script')->remove;
//to remove css style tag
$style = $description->find('style')->remove;
// to remove a div with class name findify-element
$findify = $description->find('div.findify-element')->remove;
谢谢您的回复。我不明白为什么要使用$src变量?这会保存这个对象$html->find('div#product_description')吗?不,它只是一个保存html的变量,所以我可以将它传递给
str_get_html
函数,只是为了让代码完全功能化以供演示。非常感谢。我没有使用$html=str\u get\u html($src);和$src变量。这是我使用的代码。foreach($html->find('div#ProductDescription_Tab')作为$description){$comments=$description->find('.hsn_comments',0);$comments->outertext='';print$description->outertext;}