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)


問題描述

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));

(by Munibnickbdidierc)

參考文件

  1. How to get the style property name using PHP xpath (CC BY‑SA 3.0/4.0)

#domdocument #PHP #xpath






相關問題

PHP/DOMDocument: unset() 不釋放資源 (PHP/DOMDocument: unset() does not release resources)

C++ Xerces Parser 加載 HTML 並蒐索 HTML 元素 (C++ Xerces Parser Load HTML and Search for HTML Elements)

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)

DOMDocument:如何解析類似 bbcode 的標籤? (DOMDocument : how to parse a bbcode like tag?)

如何使用 DOMDocument 獲取此 html 中的 url (How to use DOMDocument to get url in this html)

DomDocument 未能為 RSS 提要添加“鏈接”元素 (DomDocument failing to add a "link" element for RSS feed)

如何防止將文檔類型添加到 HTML 中? (How to prevent the doctype from being added to the HTML?)

PHP DOM 文檔回顯問題 (PHP DOMdocument echoing problem)

使用 PHP 將數據放到服務器上(新的 DOMdocument 不起作用) (Use PHP to put data onto server ( new DOMdocument not working))

有沒有辦法構建類似於 DOMDocument 構建 HTML 文檔的 SQL 查詢? (Is there a way to build SQL queries similar to how DOMDocument builds HTML document?)

來自 URL 的 file_get_contents 僅適用於本地服務器 (file_get_contents from URL works on local server only)

使用多個 <table> 標記抓取 HTML 頁面並從特定的 <a> 標記後代中提取文本 (Scrape HTML page with multiple <table> tags and extract text from specific <a> tag descendants)







留言討論