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

Mun*_*nib 1 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;
}
Run Code Online (Sandbox Code Playgroud)

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

nic*_*ckb 5

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

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

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

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);
Run Code Online (Sandbox Code Playgroud)