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

吾爱主题 阅读:115 2021-10-20 13:15:00 评论:0

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

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

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 /**   * 初始化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 对象。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 /**   * 获取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 ''; }

示例

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?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 );    ?>

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

原文链接:https://www.cnblogs.com/wangluochong/p/13222665.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容