PHP xpath提取网页数据内容代码解析

编程入门 行业动态 更新时间:2024-10-14 20:21:25

想要使用xpath来解析html内容, php自带两个对象

domdocument,domxpath,其中初始化 loadhtml一般都会报很多警告,但是并不影响使用,用@屏蔽错误。

/** * 初始化domxpath对象 * * @param [type] $content 网页内容 * @param [array] $pathinfo 匹配信息 * * @return void */ private function _createxpathobj($content, $patinfo) { // 如果没有xpath配置项,不初始化xpath if (!$this->_existsxpathparse($patinfo)) { return; } try { $dom = new \domdocument(); @$dom->loadhtml($content); $dom->normalize(); $xpath = new \domxpath($dom); $this->xpathobj = $xpath; } catch (\exception $e) { getservice('logger')->warning('parse html fail', ['content' => $content]); } }

其中 $node 为 domelement 对象。

/** * 获取xpath解析值 * * @param [type] $pat 匹配模式 * * @return string */ private function _getxpathfield($pat) { $objs = $this->xpathobj->query($pat); if ($objs->length > 0) { $node = $objs->item(0); $outerhtml = $node->ownerdocument->savehtml($node); return trim($outerhtml); # 作为示例 输出innerhtml //$innerhtml = ''; //foreach ($node->childnodes as $childnode){ // $innerhtml .= $childnode->ownerdocument->savehtml($childnode); //} //return $innerhtml; # 作为示例 输出文本不含标签 //return $node->textcontent; //$node->nodevalue; } return ''; }

示例

<?php $dom = new domdocument('1.0','utf-8'); $dom->loadhtml('<html><body><div><p>p1</p><p>p2</p></div></body></html>'); $node = $dom->getelementsbytagname('div')->item(0); $outerhtml = $node->ownerdocument->savehtml($node); $innerhtml = ''; foreach ($node->childnodes as $childnode){ $innerhtml .= $childnode->ownerdocument->savehtml($childnode); } echo '<h2>outerhtml: </h2>'; echo htmlspecialchars($outerhtml); echo '<h2>innerhtml: </h2>'; echo htmlspecialchars($innerhtml); ?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

PHP xpath提取网页数据内容代码解析

本文发布于:2023-06-11 00:14:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/622022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   网页   内容   数据   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!