如何使用PHP查找HTML中的所有元素并获得所有位置?
我试图在HTML中找到标记的所有元素,并获得起点和终点 这是我的HTML示例如何使用PHP查找HTML中的所有元素并获得所有位置?,php,html,arrays,html-parsing,Php,Html,Arrays,Html Parsing,我试图在HTML中找到标记的所有元素,并获得起点和终点 这是我的HTML示例 some content <iframe></iframe> <iframe></iframe> another content 获取元素的数量很容易,但我不确定HtmlComparser是否能够获得开始和结束位置 我想要的是 array( 'hasIFrame' => true, 'numberOfElements => 2, array (
some content <iframe></iframe> <iframe></iframe> another content
获取元素的数量很容易,但我不确定HtmlComparser是否能够获得开始和结束位置
我想要的是
array(
'hasIFrame' => true,
'numberOfElements => 2,
array (
0 => array (
'start' => $firstStartingElement,
'end' => $firstEndingElement
),
1 => array (
'start' => $secondStartingElement,
'end' => $secondEndingElement
)
)
如果查看官方文档(),您可以很容易地发现DOM中有多少类型的元素:
// Find all images
foreach($html->find('img') as $element) {
echo $element->src . '<br>';
}
//查找所有图像
foreach($html->find('img')作为$element){
echo$element->src.“
”;
}
您只需检索$html->find('iframe')并验证其大小,以了解是否至少存在一次,您可以执行以下操作:
$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
);
$html=“一些内容另一个内容”;
preg_match_all(“//”、$html、$iframesStartPositions、preg_OFFSET_CAPTURE);
preg_match_all(“//”、$html、$iframesEndPositions、preg_OFFSET_CAPTURE);
$iframesPositions=array();
foreach($dom->find('iframe')作为$key=>$iframe){
$iframesPositions[]=数组(
“开始”=>$iframesStartPositions[0][$key][1],
'end'=>$iframesEndPositions[0][$key][1]+9//9是结束标记的长度
);
}
返回数组(
“hasIFrame”=>count($iframesPositions)>0,
“numberOfElements”=>count($iframesPositions),
“位置”=>$iframesPositions
);
我还需要元素的位置。不确定lib是否也提供了这种功能?文档中没有提供这种功能的任何示例,但您可以通过一些技巧来获得所需的功能。如果有一种方法可以检索和迭代所有子元素,那么您可以扣除一个位置开始和结束位置是什么意思?元素在标记中的位置。字符串本身在整个字符串标记中的位置?
$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
);