急速に進化する 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 セレクター機能により、最新の CSS ベースの要素選択が PHP DOMDocument 拡張機能に導入されました。これは、JavaScript で広く使用されている querySelector() メソッドと querySelectorAll() メソッドの機能を模倣しており、開発者が CSS セレクターを使用して DOM ツリー内の要素を選択できるようにします。
これらのメソッドにより、開発者は複雑な CSS セレクターを使用して要素を選択できるため、DOM の操作がよりシンプルかつ直感的になります。
DOM セレクターはどのように機能しますか?
PHP 8.4 では、DOM 拡張機能に querySelector() と querySelectorAll() という 2 つの強力なメソッドが導入され、JavaScript と同じように CSS セレクターを使用して DOM 要素をより簡単かつ直感的に選択できるようになりました。
(https://scrapfly.io/blog/css-selector-cheatsheet/)
1.querySelector()
querySelector() メソッドを使用すると、指定された CSS セレクターに一致する 単一要素 を DOM から選択できます。
構文 :
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);
WebスクレイピングAPIでパワーアップ
ScrapFly は、大規模なデータ収集のための Web スクレイピング、スクリーンショット、抽出 API を提供します。
- ボット対策保護バイパス - ブロックせずに Web ページをスクレイピング!
- ローテーション レジデンシャル プロキシ - IP アドレスと地理的ブロックを防ぎます。
- JavaScript レンダリング - クラウド ブラウザを通じて動的 Web ページをスクレイピングします。
- 完全なブラウザ自動化 - ブラウザを制御してオブジェクトをスクロール、入力、クリックします。
- 形式変換 - HTML、JSON、テキスト、またはマークダウンとしてスクレイピングします。
- Python と Typescript SDK、および Scrapy とノーコード ツールの統合。
無料でお試しください!
Scrapfly について詳しく
PHP 8.4 DOM セレクターの制限事項
DOM セレクター API は強力なツールですが、留意すべき制限がいくつかあります。
1. 古いバージョンでは利用できません
新しい DOM セレクター メソッドは、PHP 8.4 以降でのみ使用できます。以前のバージョンを使用している開発者は、getElementById() や getElementsByTagName() などの古い DOM メソッドに依存する必要があります。
2. 静的ノードリスト
querySelectorAll() メソッドは static 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 要素を選択できるようになりました。これは、getElementsByTagName() などのメソッドを手動で繰り返す必要があり、柔軟性が低かったため、以前の PHP バージョンでは不可能でした。
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 中国語 Web サイトの他の関連記事を参照してください。

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

PhpisusedForsedingEmailsDueToitsIttegration withServerMailServicesAndExternalSmtpproviders、自動化とMarketingCampaign.1)SetupYourphpenvironment withebeBironment witheBiserverandphp、保証

メールを送信する最良の方法は、PHPMailerライブラリを使用することです。 1)Mail()関数を使用することはシンプルですが信頼できないため、電子メールがスパムを入力するか、配信できない場合があります。 2)PHPMailerは、より良い制御と信頼性を提供し、HTMLメール、添付ファイル、SMTP認証をサポートします。 3)SMTP設定が正しく構成されていることを確認し、暗号化(StartTLSやSSL/TLSなど)を使用してセキュリティを強化します。 4)大量の電子メールについては、メールキューシステムを使用してパフォーマンスを最適化することを検討してください。

customedersandaddadvancedfeaturesinphpemailentalitylivainability.1)customederadddetadata fortrackingandcategorization.2)htmLemailsallowStingtintintintintintinteractivity.3)添付物質の添付物質の添付

PHPとSMTPを使用してメールを送信することは、PHPMailerライブラリを介して実現できます。 1)PHPMailerをインストールして構成する、2)SMTPサーバーの詳細を設定する、3)電子メールコンテンツを定義し、4)メールを送信してエラーを処理します。この方法を使用して、電子メールの信頼性とセキュリティを確保します。

BestappRoachforseminginphpisusingthephpmailerlibrarydueToitsReliability、featurrichness、andeaseofuse.phpmailerSupportssmtpは、detairederorhandlingを提供します

依存関係注射(DI)を使用する理由は、コードのゆるい結合、テスト可能性、および保守性を促進するためです。 1)コンストラクターを使用して依存関係を注入します。2)サービスロケーターの使用を避け、3)依存関係噴射コンテナを使用して依存関係を管理する、4)依存関係を注入することでテスト可能性を向上させる、5)注入依存性を回避、6)パフォーマンスに対するDIの影響を考慮します。

phpperformancetuningisucial cuseenhancess andandandadsand。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

mPDF
mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。
