PHP的有些技巧可能大家并不常用到,比如DOM相关的对象。
这些方法几乎和Javascript一样的方便,轻松一句就能获取到HTML DOM节点的数据。
相比于使用正则表达式,这个方法更简单快捷。
我就就常用DOMDocument和XPath两个类做一个介绍。
假设有这样一个HTML页面(部分),其内容如下:
$html = <<
Welcome PHP!
HTML;
我们把它赋值给字符串变量$html。
我们将$html加载到DOM对象,再用DOMXPath解析处理。
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
1 DOMXPath用法
接下来我们将用DOMXPath的方法来解析。
DOMXPath有两个核心的部分:传入的表达式和返回值。
2 获取img src
获取第一个图片的src内容:
echo $src = $xpath->evaluate('string(//img/@src)');
/*输出:
/images/img1.jpg
*/
获取全部IMG SRC内容
$nodeList = $xpath->query("//img");
$srcList = [];
foreach ($nodeList as $node) {
$srcList[] = $node->attributes->getNamedItem('src')->nodeValue;
}
print_r($srcList);
/*输出:
Array
(
[0] => /images/img1.jpg
[1] => /images/img2.jpg
[2] => /images/img3.jpg
)
*/
3 获取特定class DOM
获取所有class等于content的id值,这里class值必须是唯一的:
$nodeList = $xpath->query('//*[@class="icon"]');
$result = [];
foreach ($nodeList as $node) {
$result[] = $node->attributes->getNamedItem('id')->nodeValue;
}
print_r($result);
/*输出:
Array
(
[0] => content
)
*/
获取所有class包含icon的节点的id值:
$nodeList = $xpath->query('//*[contains(@class, "icon")]');
$result = [];
foreach ($nodeList as $node) {
$result[] = $node->attributes->getNamedItem('id')->nodeValue;
}
print_r($result);
/*输出:
Array
(
[0] => img2
[1] => img3
[2] => content
)
*/
获取所有class包含icon的节点的完整HTML内容:
$nodeList = $xpath->query('//*[contains(@class, "icon")]');
$result = [];
foreach ($nodeList as $node) {
$result[] = $dom->saveHTML($node);
}
print_r($result);
/*输出:
Array
(
[0] =>
[1] =>
[2] =>
Welcome PHP!
)
*/
参考地址: