简体   繁体   English

从简单 Html Dom 中排除不需要的 html - PHP

[英]Exclude non wanted html from Simple Html Dom - PHP

I am using HTML Simple Dom Parser with PHP to get title, description and images from a website.我正在使用 HTML 简单 Dom 解析器和 PHP 从网站获取标题、描述和图像。 The issue I am facing is I am getting the html which I dont want and how to exclude those html tags.我面临的问题是我得到了我不想要的 html 以及如何排除那些 html 标签。 Below is the explanation.下面是解释。

Here is a sample html structure which is being parsed.这是正在解析的示例 html 结构。

<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>

I am using below php script to parse,我使用下面的 php 脚本来解析,

foreach($html->find('div#product_description') as $description)
{
    echo $description->outertext ;
    echo "<br>";
}

The above code parses everything inside the div with id "product_description".上面的代码解析了 id 为“product_description”的 div 中的所有内容。 What I want to exclude the div with Id "comments".我想用 Id“评论”排除 div。 I tried to convert this into string and then used substr to exclude the last character but thats not working.我尝试将其转换为字符串,然后使用 substr 排除最后一个字符,但这不起作用。 Dont know why.不知道为什么。 Any idea about how can I do this?关于我该怎么做的任何想法? Any approach that will allow me to exclude the div from parsed html will work.任何允许我从解析的 html 中排除 div 的方法都可以。 Thanks谢谢

You can remove the elements you don't want by setting their outertext = '' :您可以通过设置它们的outertext = ''来删除不需要的元素:

$src =<<<src
<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 don't want -->                                                                                                                                        
    <div id="comments">
        <h1> Some Text </h1>
    </div>

</div>
src;

$html = str_get_html($src);

foreach($html->find('#product_description') as $description)
{
    $comments = $description->find('#comments', 0); 
    $comments->outertext = ''; 
    print $description->outertext ;
}

Ok So i figured out myself just use Advanced Html Dom library its totally compatible with simple html dom & by using it you will get much more control.好的,所以我发现自己只需使用 Advanced Html Dom 库,它与简单的 html dom 完全兼容,通过使用它,您将获得更多控制权。 Its very simple to remove what you want from parsed html.从解析的 html 中删除您想要的内容非常简单。 For Ex.对于前。

//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;

enter link description here在此处输入链接描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM