這裏廢鋼一個div HTML標籤是什麼,我想要做 例爲例:如何使用PHP簡單的HTML DOM或捲曲
<div class='room'>
<h1>This is a h1</h1>
<p>This is a Paragraph</p>
<h2>This is h2</h2>
</div>
從上面的emaple我想放棄的數據和標籤在數組中。 在結果中我想要一個數組包含: arr = [h1,p,h2]; 和另一個陣列: arr2 = [這是h1,這是段落,這是h2]
這裏廢鋼一個div HTML標籤是什麼,我想要做 例爲例:如何使用PHP簡單的HTML DOM或捲曲
<div class='room'>
<h1>This is a h1</h1>
<p>This is a Paragraph</p>
<h2>This is h2</h2>
</div>
從上面的emaple我想放棄的數據和標籤在數組中。 在結果中我想要一個數組包含: arr = [h1,p,h2]; 和另一個陣列: arr2 = [這是h1,這是段落,這是h2]
$str = <<<EOF
<div class='room'>
<h1>This is a h1</h1>
<p>This is a Paragraph</p>
<h2>This is h2</h2>
</div>
EOF;
$html = str_get_html($str);
foreach($html->find('.room *') as $el){
$arr[] = $el->tag;
$arr2[] = $el->text();
}
試試這個;
$str = "<div class='room'>
<h1>This is a h1</h1>
<p>This is a Paragraph</p>
<h2>This is h2</h2>
</div>";
$arr = explode(PHP_EOL, $str);
$res =array();
Foreach($arr as $row){
If(!strpos($row, "div") !== False){
$res[substr($row, 1, strpos($row, ">")-1)] = strip_tags($row);
}
}
Var_dump($res);
它通過循環一個線的時間和創建與名爲鍵陣列。
編輯,如果有一個以上的房間,你可以把它多維像這樣:
https://3v4l.org/DdXVd
$str = "<div class='room'>
<h1>This is a h1</h1>
<p>This is a Paragraph</p>
<h2>This is h2</h2>
</div>
<div class='room2'>
<h1>This is a h1</h1>
<p>This is a Paragraph</p>
<h2>This is h2</h2>
</div>";
$arr = explode(PHP_EOL, $str);
$res =array();
Foreach($arr as $row){
If(strpos($row, "div") !== False){
$pos1 = strpos($row, "'")+1;
$room = substr($row, $pos1, strpos($row, "'", $pos1)-$pos1);
}Else{
$pos1 = strpos($row, "<")+1;
$res[$room][substr($row, strpos($row, "<")+1, strpos($row, ">")-$pos1)] = trim(strip_tags($row));
}
}
Var_dump($res);
假設已知可以使用的元素domdocument的getelementsbytagname這樣的:
$html = "<div class='room'>
<h1>This is a h1</h1>
<p>This is a Paragraph</p>
<h2>This is h2</h2>
</div>";
$doc = new DOMDocument();
$doc->loadhtML($html);
$elements = array();
$content = array();
function iterate_elements($array, $doc){
global $elements, $content;
foreach($array as $element){
$the_element = $doc->getElementsByTagName($element);
foreach($the_element as $target){
$content[] = $target->textContent;
//$target->tagName;
}
if(!empty($the_element->length)) {
$elements[] = $element;
}
}
}
iterate_elements(array('h1','p', 'h2'), $doc);
print_r($elements);
print_r($content);
嘗試下面的代碼。
$html = "<div class='room'>
<h1>This is a h1</h1>
<p>This is a Paragraph</p>
<h2>This is h2</h2>
</div>";
$dom = new SimpleXMLElement($html);
$values = array_filter(array_values((array) $dom), function ($i) { return ! is_array($i); });
$keys = array_filter(array_keys((array) $dom), function ($i) { return $i != '@attributes'; });
print_r($values); // This is a h1, This is a Paragraph, This is h2
print_r($keys); // h1, p, h2
我用array_filter
從結果中刪除div標籤。
對我最合適 –