我需要获取所有具有样式属性的标签
$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/