問題描述
Cách lấy tên thuộc tính kiểu bằng PHP xpath (How to get the style property name using PHP xpath)
I need to get all the tags having style attribute
$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;
}
but it is ouputing nothing. What is the error in my code?? Moreover, I also want to get only the CSS PRoperty name in the style, such like font‑size, font‑weight, font‑family and not their values.
參考解法
方法 1:
You just need one more forward‑slash in your expression:
foreach( $xp‑>query('//*[@style]') as $node) {
echo $node‑>tagName . " = " . $node‑>getAttribute('style') . "\n";
}
This will print (note that it keeps the line breaks in the existing attributes):
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);
方法 2:
The xpath selector is
//*[@style]
For the style content, you will have to parse it, which means
$attr_names = array_map( function($v){ return (explode(':',$v))[0];},
explode(';',$style));