[英]How to find all element with PHP Simple HTML DOM Parser?
// Find all element has attribute id
$ret = $html->find('*[id]');
這是查找所有具有屬性ID的元素的示例。 有什么辦法可以找到所有元素。 我以這種方式嘗試,但沒有用:
// Find all element
$ret = $html->find('*');
我想獲取$ html中的所有元素,所有父元素和子元素都將被獲取。 例:
<div>
<span>
<div>World!</div>
<div>
<span>Hello!</span>
<span>
<div>Hello World!</div>
</span>
</div>
</span>
</div>
現在,我想轉義所有<span>
並保留其純文本,並保留所有<div>
! 預期結果:
<div>
<div>World!</div>
<div>
<div>Hello World!</div>
</div>
</div>
您的示例似乎運行良好,請嘗試以下操作,這將輸出每個元素的內部文本。
foreach($html->find('*') as $test)
echo $test->innertext;
例如:
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
輸出
HelloWorld
/**
* Refine the input HTML (string) and keep what was specified
*
* @param $string : Input HTML
* @param array $allowed : What will be kept?
* @return bool|simple_html_dom
*/
function crl_parse_html($string, $allowed = array())
{
// String --> DOM Elements
$string = str_get_html($string);
// Fetch child of the current element (one by one)
foreach ($string->find('*') as $child) {
if (
// Current inner-text contain one or more elements
preg_match('/<[^<]+?>/is', $child->innertext) and
// Current element tag is in maintained elements array
in_array($child->tag, $allowed)
) {
// Assign current inner-text to current filtered inner-text
$child->innertext = crl_parse_html($child->innertext, $allowed);
} else if (
// Current inner-text contain one or more elements
preg_match('/<[^<]+?>/is', $child->innertext) and
// Current element tag is NOT in maintained elements array
!in_array($child->tag, $allowed)
) {
// Assign current inner-text to the set of inner-elements (if exists)
$child->innertext = preg_replace('/(?<=^|>)[^><]+?(?=<|$)(<[^\/]+?>.+)/is', '$1', $child->innertext);
// Assign current outer-text to current filtered inner-text
$child->outertext = crl_parse_html($child->innertext, $allowed);
} else if (
(
// Current inner-text is only plaintext
preg_match('/(?<=^|>)[^><]+?(?=<|$)/is', $child->innertext) and
// Current element tag is NOT in maintained elements array
!in_array($child->tag, $allowed)
) or
// Current plain-text is empty
trim($child->plaintext) == ''
) {
// Assign current outer-text to empty string
$child->outertext = '';
}
}
return $string;
}
這是我的解決方案,我做到了,如果有人需要它,我就在這里發布,然后結束這個問題。
注意:此函數使用遞歸。 因此,太大的數據將是一個大問題。 在決定使用此功能時,請仔細考慮。
GLOBAL $elements;
$elements=array();
findElements($fullHTML);
function findElements($html){
global $elements;
$art_html = new simple_html_dom();
$art_html->load($html);
foreach ($art_html->find("*") as $element) {
$elements[]=$element;
findElements($element->innertext);
}
}
我寫這個函數來查找所有元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.