【问题标题】:How to use PHP to find all elements in HTML and get all the positions?如何使用 PHP 查找 HTML 中的所有元素并获取所有位置?
【发布时间】:2015-07-23 12:10:10
【问题描述】:

我正在尝试在 HTML 中查找标签的所有元素并获取起点和终点。

这是我的示例 HTML

some content <iframe></iframe> <iframe></iframe> another content

这是我目前得到的代码。

$dom = HtmlDomParser::str_get_html($this->content);

$iframes = array();
foreach( $dom->find( 'iframe' ) as $iframe) {
    $iframes[] = $iframe;
}

return array(
    'hasIFrame' =>  count( $iframes ) > 0
);

获取元素个数很简单,但是不知道HTMLDomParser能不能获取到开始和结束的位置?

我想要的是

array( 
 'hasIFrame' => true,
 'numberOfElements => 2,
 array ( 
  0 => array (
   'start' => $firstStartingElement,
   'end'   => $firstEndingElement
  ),
  1 => array ( 
   'start' => $secondStartingElement,
   'end'   => $secondEndingElement
  )
)

【问题讨论】:

  • 开始和结束位置是什么意思?
  • 元素在标签中的位置。
  • 字符串本身在整个字符串标记中的位置?

标签: php html arrays html-parsing


【解决方案1】:

如果您查看官方文档 (http://simplehtmldom.sourceforge.net/),您可以轻松找出 DOM 中有多少类型的元素:

// Find all images 
foreach($html->find('img') as $element) {
       echo $element->src . '<br>';
}

您所要做的就是检索 $html->find('iframe') 并验证其大小以了解是否至少存在一次

【讨论】:

  • 我也想要元素的位置。不确定该库是否也提供了该功能?
  • 该文档没有提供任何此类功能的示例,但您可以通过一些技巧来获得您想要的。如果有办法检索和遍历所有孩子,那么你可以扣除一个位置
【解决方案2】:

你可以这样做:

$html = "some content <iframe></iframe> <iframe></iframe> another content";
preg_match_all('/<iframe>/', $html, $iframesStartPositions, PREG_OFFSET_CAPTURE);
preg_match_all('/<iframe\/>/', $html, $iframesEndPositions, PREG_OFFSET_CAPTURE);


$iframesPositions = array();
foreach( $dom->find( 'iframe' ) as $key => $iframe) {
    $iframesPositions[] = array(
      'start' => $iframesStartPositions[0][$key][1],
      'end'   => $iframesEndPositions[0][$key][1] + 9 // 9 is the length of the ending tag <iframe/>
    );
}

return array(
    'hasIFrame'        =>  count($iframesPositions) > 0,
    'numberOfElements' => count($iframesPositions),
    'positions'        =>  $iframesPositions
);

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    相关资源
    最近更新 更多