首页 > 解决方案 > 是否可以从 php 中的 htmlentities() 函数中提取 Dom 元素?

问题描述

感谢您花时间尝试帮助我解决我的问题。所以我正在做的是从一个链接尝试一个 html 解析器。因此,我首先使用 curl 链接到网站,然后将其转换为 htmlentities(),因此它不会加载到页面上,因此我从中获取了一个字符串,然后我使用 DOM 对象从中提取标签。我在谷歌搜索上检查了解析器的不同方法,所以我了解了一点,然后我执行了我的脚本,但问题是字符串被保存为 textCont 而不是真正的 html 文档,所以我想知道如何将 htmlentities 字符串转换为真正的 dom 文档并从中提取元素? var_dump 的图像在 这里是我的脚本:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://www.usatoday.com/story/news/world/2021/02/17/dubai-princess-sheikha-latifa-says-she-hostage-after-flee-attempt/6778014002/?utm_source=feedblitz&utm_medium=FeedBlitzRss&utm_campaign=usatodaycomworld-topstories');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($curl);
curl_close($curl);

$htmlentities = htmlentities($result);
// I added the code here 
$htmlDom = new DOMDocument();
$htmlDom->loadHTML($htmlentities);
$htmlDom->preserveWhiteSpace = false; 
$styles = $htmlDom->getElementsByTagName('style');

foreach ($styles as $style) {
    
    $item = $style->getElementsByTagName('td'); 

    //echo the values 
    echo '1: '.$item->item(0)->nodeValue.'<br />'; 
    echo '2: '.$item->item(1)->nodeValue.'<br />'; 
    echo '3: '.$item->item(2)->nodeValue;  
 }

编辑:

我在代码旁边添加的是:

$htmlentities = htmlentities($result);
$htmlentities = str_replace("&quot;",'"', $htmlentities);
$htmlentities = str_replace("&#039;","'", $htmlentities);
$htmlentities = str_replace("&lt;","<", $htmlentities);
$htmlentities = str_replace("&gt;",">", $htmlentities);

libxml_use_internal_errors(true);
$htmlDom = new DOMDocument();
$htmlDom->loadHTML($htmlentities);

libxml_clear_errors();
var_dump($htmlDom);

标签: phphtmlhtml-parsing

解决方案


推荐阅读