在快速發展的 PHP 領域,每個新版本都引入了簡化和現代化開發工作流程的功能。 PHP 8.4 也不例外,它為 DOM 擴充添加了期待已久的增強功能。引入了一項新功能,可顯著增強開發人員與 DOM 元素的互動方式。
在本文中,我們將深入了解 PHP 8.4 中的新 DOM 選擇器功能、其語法、用例以及它如何簡化 DOM 元素的使用。
PHP 8.4 有什麼新功能? DOM 選擇器
PHP 8.4 引入了 DOM 擴充功能的重大更新,增加了 DOM 選擇器 API,讓開發者更直觀、更靈活地選擇和操作元素。
以前,開發人員依賴 gnetElementsByTagName()、getElementById() 和 querySelector() 等方法,這些方法功能強大,但冗長且不太直觀。這些方法需要手動迭代和選擇邏輯,使得程式碼更難維護。
使用 PHP 8.4,開發人員可以使用類似 JavaScript 的原生 CSS 選擇器語法,以實現更靈活和可讀的元素選擇。此變更簡化了程式碼,尤其是在處理複雜或深層巢狀的 HTML 和 XML 文件時。
什麼是 DOM 選擇器?
PHP 8.4 中引入的 DOM 選擇器功能為 PHP DOMDocument 擴充功能帶來了現代的基於 CSS 的元素選擇。它模仿 JavaScript 廣泛使用的 querySelector() 和 querySelectorAll() 方法的功能,使開發人員能夠使用 CSS 選擇器選擇 DOM 樹中的元素。
這些方法允許開發人員使用複雜的 CSS 選擇器來選擇元素,從而使 DOM 操作更加簡單和直觀。
DOM 選擇器如何運作?
在 PHP 8.4 中,DOM 擴充功能引入了兩個強大的方法:querySelector() 和 querySelectorAll(),以便使用 CSS 選擇器更輕鬆、更直觀地選擇 DOM 元素,就像在 JavaScript 中一樣。
(https://scrapfly.io/blog/css-selector-cheatsheet/)
1. 查詢選擇器()
querySelector() 方法可讓您從 DOM 中選擇與指定 CSS 選擇器相符的單一元素。
文法 :
DOMElement querySelector(string $selector)
範例 :
$doc = new DOMDocument(); $doc->loadHTML('<div> <p>This method returns the <strong>first element</strong> matching the provided CSS selector. If no element is found, it returns null.</p> <h4> 2. querySelectorAll() </h4> <p>The querySelectorAll() method allows you to select <strong>all elements</strong> matching the provided CSS selector. It returns a DOMNodeList object, which is a collection of DOM elements.</p> <p><strong>Syntax</strong> :<br> </p> <pre class="brush:php;toolbar:false">DOMNodeList querySelectorAll(string $selector)
範例 :
$doc = new DOMDocument(); $doc->loadHTML('<div> <p>This method returns a DOMNodeList containing all elements matching the given CSS selector. If no elements are found, it returns an empty DOMNodeList.</p> <h2> Key Benefits of the DOM Selector </h2> <p>CSS selector in PHP 8.4 brings several key advantages to developers, the new methods streamline DOM element selection, making your code cleaner, more flexible, and easier to maintain.</p> <h3> 1. Cleaner and More Intuitive Syntax </h3> <p>With the new DOM selector methods, you can now use the familiar CSS selector syntax, which is much more concise and readable. No longer do you need to write out complex loops to traverse the DOM just provide a selector, and PHP will handle the rest.</p> <h3> 2. Greater Flexibility </h3> <p>The ability to use CSS selectors means you can select elements based on attributes, pseudo-classes, and other criteria, making it easier to target specific elements in the DOM.</p> <p>For example, you can use:</p> <ul> <li>.class</li> <li>#id</li> <li>div > p:first-child</li> <li>[data-attribute="value"]</li> </ul> <p>This opens up a much more powerful and flexible way of working with HTML and XML documents.</p> <h3> 3. Improved Consistency with JavaScript </h3> <p>For developers familiar with JavaScript, the new DOM selector methods will feel intuitive. If you’ve used querySelector() or querySelectorAll() in JavaScript, you’ll already be comfortable with their usage in PHP.</p> <h2> Comparison with Older PHP DOM Methods </h2> <p>To better understand the significance of these new methods, let's compare them to traditional methods available in older versions of PHP.</p> <div><table> <thead> <tr> <th><strong>Feature</strong></th> <th><strong>Old Method</strong></th> <th><strong>New DOM Selector</strong></th> </tr> </thead> <tbody> <tr> <td>Select by ID</td> <td>getElementById('id')</td> <td>querySelector('#id')</td> </tr> <tr> <td>Select by Tag Name</td> <td>getElementsByTagName('tag')</td> <td>querySelectorAll('tag')</td> </tr> <tr> <td>Select by Class Name</td> <td>Loop through getElementsByTagName() </td> <td>querySelectorAll('.class')</td> </tr> <tr> <td>Complex Selection</td> <td>Not possible</td> <td>querySelectorAll('.class > tag')</td> </tr> <tr> <td>Return Type (Single Match)</td> <td>DOMElement</td> <td>`DOMElement</td> </tr> <tr> <td>Return Type (Multiple)</td> <td>{% raw %}DOMNodeList (live)</td> <td> DOMNodeList (static)</td> </tr> </tbody> </table></div> <h2> Practical Examples </h2> <p>Let’s explore some practical examples of using the DOM selector methods in PHP 8.4. These examples will show how you can use CSS selectors to efficiently target elements by ID, class, and even nested structures within your HTML or XML documents.</p> <h3> By ID </h3> <p>The querySelector('#id') method selects a unique element by its id, which should be unique within the document. This simplifies targeting specific elements and improves code readability.<br> </p> <pre class="brush:php;toolbar:false">$doc = new DOMDocument(); $doc->loadHTML('<div> <p>This code selects the element with the> </p> <h3> By Class </h3> <p>The querySelectorAll('.class') method selects all elements with a given class, making it easy to manipulate groups of elements, like buttons or list items, in one go.<br> </p> <pre class="brush:php;toolbar:false">$doc = new DOMDocument(); $doc->loadHTML('<div> <p>This code selects all elements with the class item and outputs their text content. It’s ideal for working with multiple elements that share the same class name.</p> <h3> Nested Elements </h3> <p>The querySelectorAll('.parent > .child') method targets direct children of a specific parent, making it easier to work with nested structures like lists or tables.<br> </p> <pre class="brush:php;toolbar:false">$doc = new DOMDocument(); $doc->loadHTML('
- elements that are direct children of the .list class and outputs their text content. The > combinator ensures only immediate child elements are selected, making it useful for working with nested structures.
Example Web Scraper using Dom Selector
Here's an example PHP web scraper using the new DOM selector functionality introduced in PHP 8.4. This script extracts product data from the given product page:
<?php // Load the HTML of the product page $url = 'https://web-scraping.dev/product/1'; $html = file_get_contents($url); // Create a new DOMDocument instance and load the HTML $doc = new DOMDocument(); libxml_use_internal_errors(true); // Suppress warnings for malformed HTML $doc->loadHTML($html); libxml_clear_errors(); // Extract product data using querySelector and querySelectorAll $product = []; // Extract product title $titleElement = $doc->querySelector('h1'); $product['title'] = $titleElement ? $titleElement->textContent : null; // Extract product description $descriptionElement = $doc->querySelector('.description'); $product['description'] = $descriptionElement ? $descriptionElement->textContent : null; // Extract product price $priceElement = $doc->querySelector('.price'); $product['price'] = $priceElement ? $priceElement->textContent : null; // Extract product variants $variantElements = $doc->querySelectorAll('.variants option'); $product['variants'] = []; if ($variantElements) { foreach ($variantElements as $variant) { $product['variants'][] = $variant->textContent; } } // Extract product image URLs $imageElements = $doc->querySelectorAll('.product-images img'); $product['images'] = []; if ($imageElements) { foreach ($imageElements as $img) { $product['images'][] = $img->getAttribute('src'); } } // Output the extracted product data echo json_encode($product, JSON_PRETTY_PRINT);
使用網頁抓取 API 啟動
ScrapFly 提供網頁抓取、螢幕截圖和提取 API,用於大規模資料收集。
- 反機器人保護繞過 - 抓取網頁而不阻塞!
- 輪換住宅代理 - 防止 IP 位址和地理封鎖。
- JavaScript 渲染 - 透過雲端瀏覽器抓取動態網頁。
- 完全瀏覽器自動化 - 控制瀏覽器捲動、輸入和點擊物件。
- 格式轉換 - 抓取為 HTML、JSON、文字或 Markdown。
- Python 和 Typescript SDK,以及 Scrapy 和無程式碼工具整合。
免費試用!
更多關於 Scrapfly 的資訊
PHP 8.4 DOM 選擇器的限制
雖然 DOM 選擇器 API 是一個強大的工具,但有一些限制需要記住:
1. 舊版不可用
新的 DOM 選擇器方法僅在 PHP 8.4 及更高版本中可用。使用早期版本的開發人員將需要依賴較舊的 DOM 方法,例如 getElementById() 和 getElementsByTagName()。
2. 靜態節點列表
querySelectorAll() 方法傳回一個 靜態 DOMNodeList,這表示它不反映初始選擇後對 DOM 所做的變更。這與 JavaScript 的即時 NodeList 不同。
3. 有限的偽類支持
雖然支援基本 CSS 選擇器,但高階偽類(例如 :nth-child()、:nth-of-type())在 PHP 中可能支援有限或不支援。
4. 大文檔上的效能
在非常大的文件上使用複雜的 CSS 選擇器可能會導致效能問題,尤其是在 DOM 樹嵌套很深的情況下。
常問問題
為了總結本指南,以下是 PHP 8.4 新 DOM 選擇器的一些常見問題的解答。
PHP 8.4 有哪些主要新功能?
PHP 8.4 引入了 DOM 選擇器方法(querySelector() 和 querySelectorAll()),使開發人員能夠使用 CSS 選擇器選擇 DOM 元素,使 DOM 操作更加直觀和高效。
PHP 8.4 對 DOM 操作進行了哪些早期版本中未提供的變更?
在 PHP 8.4 中,由於引入了 querySelector() 和 querySelectorAll(),開發人員現在可以直接使用 CSS 選擇器來選擇 DOM 元素。這在早期的 PHP 版本中是不可能的,像 getElementsByTagName() 這樣的方法需要更多的手動迭代並且不太靈活。
PHP 8.4 是否支援「querySelector()」和「querySelectorAll()」中的所有 CSS 選擇器?
PHP 8.4 支援廣泛的 CSS 選擇器,但存在一些限制。例如,像 :nth-child() 和 :not() 這樣的偽類別可能不受完全支援或功能有限。
概括
PHP 8.4 引入了 DOM 選擇器 API,透過提供直覺的、基於 CSS 的選擇方法,簡化了 DOM 文件的處理。新的 querySelector() 和 querySelectorAll() 方法允許開發人員使用 CSS 選擇器輕鬆定位 DOM 元素,使程式碼更加簡潔和可維護。
雖然有些限制,但這些新方法的好處遠大於缺點。如果您使用 PHP 8.4 或更高版本,那麼值得採用此功能來簡化您的 DOM 操作任務。
This code selects the
以上是PHP 新 DOM 選擇器功能指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自動化intifications andMarketingCampaigns.1)設置設置yourphpenvenvironnvironnvironmentwithaweberswithawebserverserververandphp,確保themailfunctionisenabled.2)useabasicscruct

發送電子郵件的最佳方法是使用PHPMailer庫。 1)使用mail()函數簡單但不可靠,可能導致郵件進入垃圾郵件或無法送達。 2)PHPMailer提供更好的控制和可靠性,支持HTML郵件、附件和SMTP認證。 3)確保正確配置SMTP設置並使用加密(如STARTTLS或SSL/TLS)以增強安全性。 4)對於大量郵件,考慮使用郵件隊列系統來優化性能。

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP發送郵件可以通過PHPMailer庫實現。 1)安裝並配置PHPMailer,2)設置SMTP服務器細節,3)定義郵件內容,4)發送郵件並處理錯誤。使用此方法可以確保郵件的可靠性和安全性。

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver CS6
視覺化網頁開發工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。