我在
<li>
内有一些<div>
标签,如下所示:
<li> <a href="link1"> one <li>
<li> <a href="link2"> two <li>
<li> <a href="link3"> three <li>
如何使用 HTML DOM 解析器获取文本
two
,然后将其放入数组中以供稍后使用?
您需要确保
a
标签已关闭,然后您可以这样做:
<?php
$html = '<li> <a href="link1"> one </a> <li>
<li> <a href="link2"> two </a> <li>
<li> <a href="link3"> three </a> <li>
';
// Create a new DOM Document
$xml = new DOMDocument();
// Load the html contents into the DOM
$xml->loadHTML($html);
// Empty array to hold all links to return
$result = array();
//Loop through each <li> tag in the dom
foreach($xml->getElementsByTagName('li') as $li) {
//Loop through each <a> tag within the li, then extract the node value
foreach($li->getElementsByTagName('a') as $links){
$result[] = $links->nodeValue;
}
}
//Return the links
print_r($result);
/*
Array
(
[0] => one
[1] => two
[2] => three
)
*/
?>
考虑使用 Simple HTML Dom Parser 来实现这一点。示例代码:
// include the simple html dom parser
include 'simple_html_dom.php';
// load the html with one of the sutiable methods available with it
$html = str_get_html('<li><a href="link1">one</a></li><li><a href="link2">two</a></li>');
// create a blank array to store the results
$items = array();
// loop through "li" elements and store the magic plaintext attribute value inside $items array
foreach( $html->find('li') as $li ) $items[] = $li->plaintext;
// this should output: Array ( [0] => one [1] => two )
print_r( $items );
如果不关闭
</a>
标签,您的输入 HTML 看起来会损坏,但您仍然可以使用合法的 DOM 解析器来获取您需要的内容。 使用 XPath 将直接隔离所需的文本。 您可能希望也可能不希望修剪空格。
代码:(演示)
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
保留空格:
var_export(
array_column(
iterator_to_array($xpath->query('//li/a/text()')),
'nodeValue'
)
);
输出:
array (
0 => ' one ',
1 => ' two ',
2 => ' three ',
)
修剪空格:
var_export(
array_map(
fn($text) => trim($text->nodeValue),
iterator_to_array($xpath->query('//li/a/text()')),
)
);
输出:
array (
0 => 'one',
1 => 'two',
2 => 'three',
)