PHP的有些技巧可能大家并不常用到,比如DOM相关的对象。
这些方法几乎和Javascript一样的方便,轻松一句就能获取到HTML DOM节点的数据。
相比于使用正则表达式,这个方法更简单快捷。
我就就常用DOMDocument和DOMXPath两个类做一个介绍。
假设有这样一个HTML页面(部分),其内容如下:
$html = <<
         
         
         
        Welcome PHP!
    PHP的有些技巧可能大家并不常用到,比如DOM相关的对象。
这些方法几乎和Javascript一样的方便,轻松一句就能获取到HTML DOM节点的数据。
相比于使用正则表达式,这个方法更简单快捷。
我就就常用DOMDocument和DOMXPath两个类做一个介绍。
假设有这样一个HTML页面(部分),其内容如下:
$html = <<
         
         
         
        Welcome PHP!
    我们把它赋值给字符串变量$html。
我们将$html加载到DOM对象,再用 DOMXPath解析处理。
$dom = new DOMDocument(); $dom->loadHTML($html); $xpath = new DOMXPath($dom);
接下来我们将用 DOMXPath的方法来解析。
DOMXPath有两个核心的部分:传入的表达式和返回值。
表达式是W3C标准的XPath表达式,语法:https://www.w3schools.com/xml/xpath_syntax.asp。
返回值是DOMNodeList对象,有若干属性和方法,也是W3C标准:https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html。
获取第一个图片的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
)
*/
获取所有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] =>
    [1] =>  [2] =>
    [2] => Welcome PHP!
)
*/
参考地址: