php - 如何使用PHP xpath获取样式属性名称

标签 php xpath domdocument

我需要获取所有具有样式属性的标签

$html = '<div style="font-style: italic; text-align: center; 
background-color: red;">On The Contrary</div><span 
style="font-style: italic; background-color: rgb(244, 249, 255); 
font-size: 32px;"><b style="text-align: center; 
background-color: rgb(255, 255, 255);">This is USA</b></span>';

$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXpath($dom);

foreach ($xp->query('/*[@style]') as $node) {
    $style =  $node->getAttribute('style');
    echo $style;
}


但它没有任何要求。
我的代码有什么错误?
而且,我也只想获取样式中的CSS PRoperty名称,例如font-size,font-weight,font-family,而不是它们的值。

最佳答案

您只需要在表达式中再加上一个正斜杠:

foreach( $xp->query('//*[@style]') as $node) {
    echo $node->tagName . " = " . $node->getAttribute('style') . "\n";
}


这将进行打印(请注意,它会将换行符保留在现有属性中):

div = font-style: italic; text-align: center; 
background-color: red;
span = font-style: italic; background-color: rgb(244, 249, 255); 
font-size: 32px;
b = text-align: center; 
background-color: rgb(255, 255, 255);

关于php - 如何使用PHP xpath获取样式属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15706591/

相关文章:

php - 在 php 中使用的 ajax json 响应数组

c# - XPath 到 LINQ 的转换

browser - 使用 WebBrowser.DocumentText 和 DomDocument.DesignMode 的应用程序在 IE8 中工作,在 IE9 中不起作用

php - 将 txt 文件的内容分解为数组

php - 如何保护立即购买 Paypal 按钮?

xpath - 根据另一个元素的位置选择一个xpath元素

xml - 如何根据其他元素中的属性值限制 XML 属性的值?

domdocument - 未捕获的异常 'DOMException',消息为 'Not Found Error'

php - 使用 PHP 和 XPATH,如何获取最接近的 `h3` 的内容?

php - Go webserver 性能稳定性如何,与 Tomcat、Apache 相比,长期运行稳定性如何?