想要使用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);    
?>

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