php 解决提取html第一段文本 使用DOMDocument和DOMXPath 输出的都是乱码问题

本文详细阐述了网站系统开发过程,包括需求分析、界面设计、后端开发、数据库设计、测试和上线运营,强调了每个阶段在整体流程中的重要性及可能的变通性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
$content=<div class="cl-preview-section" style="box-sizing: border-box; color: rgba(0, 0, 0, 0.75); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-variant-ligatures: no-common-ligatures; text-wrap-mode: wrap; background-color: rgb(255, 255, 255);">
    <p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 77, 77); line-height: 26px; overflow: auto hidden; text-indent: 2em;">
        在炎热的夏季,工厂车间通常会面临高温和潮湿的困扰
    </p>
</div>
<div class="cl-preview-section" style="box-sizing: border-box; color: rgba(0, 0, 0, 0.75); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-variant-ligatures: no-common-ligatures; text-wrap-mode: wrap; background-color: rgb(255, 255, 255);">
    <p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 77, 77); line-height: 26px; overflow: auto hidden; text-indent: 2em;">
        工业能够快速降低车间的温度
    </p>
</div>;
		$dom = new \DOMDocument();
        //load之前强转字符编码
        $str2 = mb_convert_encoding($content,'HTML-ENTITIES',"UTF-8");
        @$dom->loadHTML($str2); // 使用@来抑制警告,如果HTML不完整或格式不正确
        $xpath = new \DOMXPath($dom);

        // 获取所有的div元素
        $divs = $xpath->query('//div');

        foreach ($divs as $div) {
            // 移除div的style属性
            $div->removeAttribute('style');
        }

        // 获取所有文本节点
        $texts = $xpath->query('//text()');

        $firstText = '';
        foreach ($texts as $text) {
            if (trim($text->nodeValue) !== '') { // 确保不是空白文本
                $firstText = $text->nodeValue; // 获取第一个非空文本节点
                break; // 假设我们只关心第一个段落,所以退出循环
            }
        }

        echo $firstText; // 输出: 这是第一段文字。

?>

希望能够帮助大家

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值