How can one parse HTML/XML and extract information from it?HTML/XML을 해석하고 정보를 추출하려면 어떻게 해야 합니까?
질문에 대한 답변
Native XML Extensions네이티브 XML 확장자
I prefer using one of the native XML extensions since they come bundled with PHP, are usually faster than all the 3rd party libs and give me all the control I need over the markup.네이티브 XML 확장자 중 하나를 사용하는 것을 선호합니다. 왜냐하면 그것들은 PHP에 번들되어 있고, 보통 서드 파티의 모든 lib보다 빠르고, 마크업에 필요한 모든 제어가 가능하기 때문입니다.
DOM돔
The DOM extension allows you to operate on XML documents through the DOM API with PHP 5.DOM 확장 기능을 사용하면 PHP 5에서 DOM API를 통해 XML 문서를 조작할 수 있습니다. It is an implementation of the W3C’s Document Object Model Core Level 3, a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents.W3C의 Document Object Model Core Level 3을 구현한 것으로, 플랫폼 및 언어에 구애받지 않는 인터페이스로 프로그램 및 스크립트가 문서의 내용, 구조 및 스타일에 동적으로 액세스하여 갱신할 수 있습니다.
DOM is capable of parsing and modifying real world (broken) HTML and it can do XPath queries.DOM은 실제(파손된) HTML을 해석 및 수정할 수 있으며 XPath 쿼리를 수행할 수 있습니다. It is based on libxml.libxml을 기반으로 합니다.
It takes some time to get productive with DOM, but that time is well worth it IMO. Since DOM is a language-agnostic interface, you’ll find implementations in many languages, so if you need to change your programming language, chances are you will already know how to use that language’s DOM API then.DOM을 사용하여 생산성을 얻으려면 시간이 좀 걸리지만 IMO는 충분히 가치가 있습니다.DOM은 언어에 구애받지 않는 인터페이스이기 때문에 여러 언어로 구현되어 있기 때문에 프로그래밍 언어를 변경해야 할 경우 해당 언어의 DOM API를 사용하는 방법을 이미 알고 있을 것입니다.
How to use the DOM extension has been covered extensively on StackOverflow, so if you choose to use it, you can be sure most of the issues you run into can be solved by searching/browsing Stack Overflow.DOM 확장의 사용 방법은 StackOverflow에서 폭넓게 다루어져 있기 때문에 이 확장 기능을 사용하는 경우 스택 오버플로를 검색/브라우징하는 것으로 대부분의 문제를 해결할 수 있습니다.
A basic usage example and a general conceptual overview are available in other answers.기본적인 사용 예시와 일반적인 개념적 개요는 다른 답변에서도 볼 수 있습니다.
XMLReaderXMLReader
The XMLReader extension is an XML pull parser.XMLReader 확장은 XML 풀 파서입니다. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.판독기는 문서 스트림에서 전진하고 도중에 각 노드에서 정지하는 커서 역할을 합니다.
XMLReader, like DOM, is based on libxml.XMLReader는 DOM과 마찬가지로 libxml을 기반으로 합니다. I am not aware of how to trigger the HTML Parser Module, so chances are using XMLReader for parsing broken HTML might be less robust than using DOM where you can explicitly tell it to use libxml’s HTML Parser Module.HTML 파서 모듈을 트리거하는 방법을 모르기 때문에 망가진HTML을 해석하기 위해 XMLReader를 사용하는 것은 libxml의 HTML 파서 모듈을 사용하도록 명시적으로 지시할 수 있는 DOM을 사용하는 것보다 덜 강력할 수 있습니다.
A basic usage example is available in another answer.기본적인 사용 예는 다른 답변에서 볼 수 있습니다.
XML ParserXML 파서
This extension lets you create XML parsers and then define handlers for different XML events.이 확장을 사용하면 XML 파서를 만든 다음 다른 XML 이벤트에 대한 핸들러를 정의할 수 있습니다. Each XML parser also has a few parameters you can adjust.각 XML 파서에는 조정할 수 있는 몇 가지 파라미터도 있습니다.
The XML Parser library is also based on libxml, and implements a SAX style XML push parser.XML 파서 라이브러리는 libxml을 기반으로 하며 SAX 스타일의 XML 푸시 파서를 구현합니다. It may be a better choice for memory management than DOM or SimpleXML, but will be more difficult to work with than the pull parser implemented by XMLReader.메모리 관리에는 DOM이나 SimpleXML보다 좋은 선택이지만 XMLReader에 의해 구현된 풀파서보다 사용하기 어렵습니다.
SimpleXmlSimpleXml
The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.SimpleXML 확장은 XML을 일반 속성 선택기 및 어레이 반복기로 처리할 수 있는 개체로 변환하기 위한 매우 간단하고 쉽게 사용할 수 있는 도구 세트를 제공합니다.
SimpleXML is an option when you know the HTML is valid XHTML. If you need to parse broken HTML, don’t even consider SimpleXml because it will choke.SimpleXML은 HTML이 유효한 XHTML이라는 것을 알고 있는 경우 옵션입니다.파손된HTML을 해석할 필요가 있는 경우는, SimpleXml을 고려하지 말아 주세요.
A basic usage example is available, and there are lots of additional examples in the PHP Manual.기본적인 사용 예를 이용할 수 있으며, PHP 매뉴얼에는 많은 추가 예가 있습니다.
3rd Party Libraries (libxml based)서드파티 라이브러리(libxml 기반)
If you prefer to use a 3rd-party lib, I’d suggest using a lib that actually uses DOM/libxml underneath instead of string parsing.서드파티 lib를 사용하는 경우 문자열 해석 대신 실제로 아래에 DOM/libxml을 사용하는 lib를 사용하는 것이 좋습니다.
FluentDomFluentDom
FluentDOM provides a jQuery-like fluent XML interface for the DOMDocument in PHP.FluentDOM은 PHP의 DOMDocument에 jQuery와 같은 fluent XML 인터페이스를 제공합니다. Selectors are written in XPath or CSS (using a CSS to XPath converter).실렉터는 XPath 또는 CSS로 작성됩니다(CSS-to-XPath 컨버터 사용). Current versions extend the DOM implementing standard interfaces and add features from the DOM Living Standard.현재 버전은 표준 인터페이스를 구현하는 DOM을 확장하고 DOM Living Standard에서 기능을 추가합니다. FluentDOM can load formats like JSON, CSV, JsonML, RabbitFish and others.FluentDOM은 JSON, CSV, JsonML, Rabbit Fish 등의 형식을 로드할 수 있습니다. Can be installed via Composer.Composer를 통해 설치할 수 있습니다.
HtmlPageDomHtml PageDom
Wa72HtmlPageDom
is a PHP library for easy manipulation of HTML documents using DOM.는 DOM을 사용하여 HTML 문서를 쉽게 조작할 수 있는 PHP 라이브러리입니다. It requires DomCrawler from Symfony2 components for traversing the DOM tree and extends it by adding methods for manipulating the DOM tree of HTML documents.DOM 트리를 통과하기 위해 Symfony2 컴포넌트의 DomainCrawler가 필요하며 HTML 문서의 DOM 트리를 조작하는 방법을 추가하여 확장합니다.
phpQueryphpQuery
phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library.phpQuery는 jQuery JavaScript Library를 기반으로 하는 서버 측 체인 가능한 CSS3 선택기 기반의 Document Object Model(DOM) API입니다. The library is written in PHP5 and provides additional Command Line Interface (CLI).라이브러리는 PHP5로 작성되며 추가 명령줄 인터페이스(CLI)를 제공합니다.
This is described as “abandonware and buggy: use at your own risk” but does appear to be minimally maintained.이는 “포기 및 버그: 사용자의 책임 하에 사용”이라고 설명되지만 유지보수는 최소한으로 유지되고 있는 것으로 보입니다.
laminas-dom라미나스돔
The Laminas라미나스Dom component (formerly Zend_DOM) provides tools for working with DOM documents and structures.돔 컴포넌트(이전의 Zend_DOM)는 DOM 문서 및 구조 작업을 위한 도구를 제공합니다. Currently, we offer 현재, 델은
LaminasDomQuery
, which provides a unified interface for querying DOM documents utilizing both XPath and CSS selectors.는 XPath 실렉터와 CSS 실렉터를 모두 사용하여 DOM 문서를 조회하기 위한 통합 인터페이스를 제공합니다.This package is considered feature-complete, and is now in security-only maintenance mode.이 패키지는 기능이 완료된 것으로 간주되며 현재 보안 전용 유지 보수 모드에 있습니다.
fDOMDocument기능
fDOMDocument extends the standard DOM to use exceptions at all occasions of errors instead of PHP warnings or notices.fDOMDocument는 표준 DOM을 확장하여 PHP 경고나 알림 대신 오류가 발생할 경우 예외를 사용합니다. They also add various custom methods and shortcuts for convenience and to simplify the usage of DOM.또, 편리성과 DOM 의 사용의 심플화를 위해서, 다양한 커스텀 메서드와 쇼트 컷을 추가합니다.
sabre/xmlsabre/xml
sabre/xml is a library that wraps and extends the XMLReader and XMLWriter classes to create a simple “xml to object/array” mapping system and design pattern.sabre/xml은 XMLReader 및 XMLWriter 클래스를 랩 및 확장하여 단순한 “xml to object/array” 매핑 시스템과 설계 패턴을 만드는 라이브러리입니다. Writing and reading XML is single-pass and can therefore be fast and require low memory on large xml files.XML 의 기입과 읽기는 싱글 패스이기 때문에, 큰 XML 파일에서는 고속으로 메모리가 부족할 필요가 있습니다.
FluidXMLFluidXML
FluidXML is a PHP library for manipulating XML with a concise and fluent API.FluidXML은 간결하고 유창한 API로 XML을 조작하기 위한 PHP 라이브러리입니다. It leverages XPath and the fluent programming pattern to be fun and effective.XPath와 유창한 프로그래밍 패턴을 활용하여 재미있고 효과적입니다.
3rd-Party (not libxml-based)서드파티(libxml 기반 아님)
The benefit of building upon DOM/libxml is that you get good performance out of the box because you are based on a native extension.DOM/libxml을 기반으로 구축하면 네이티브 확장을 기반으로 하므로 개봉 즉시 뛰어난 성능을 얻을 수 있습니다. However, not all 3rd-party libs go down this route.단, 모든 서드파티제의 lib가 이 경로를 따르는 것은 아닙니다. Some of them listed below그 중 일부는 다음과 같습니다.
PHP Simple HTML DOM ParserPHP Simple HTML DOM 파서
- An HTML DOM parser written in PHP5+ lets you manipulate HTML in a very easy way!HTML DOM 파서를 PHP5+로 작성하면 HTML을 쉽게 조작할 수 있습니다!
- Require PHP 5+.PHP 5+가 필요합니다.
- Supports invalid HTML.유효하지 않은 HTML을 지원합니다.
- Find tags on an HTML page with selectors just like jQuery.jQuery와 마찬가지로 선택기가 있는 HTML 페이지에서 태그를 찾습니다.
- Extract contents from HTML in a single line.HTML에서 콘텐츠를 한 줄로 추출합니다.
I generally do not recommend this parser.일반적으로 이 파서는 추천하지 않습니다. The codebase is horrible and the parser itself is rather slow and memory hungry.코드베이스가 형편없고 파서 자체가 느리고 메모리가 부족합니다. Not all jQuery Selectors (such as child selectors) are possible.일부 jQuery Selector(예: 자식 선택기)를 사용할 수 없습니다. Any of the libxml based libraries should outperform this easily.libxml 기반 라이브러리는 이 성능을 쉽게 능가합니다.
PHP Html ParserPHP HTML 파서
PHPHtmlParser is a simple, flexible, html parser which allows you to select tags using any css selector, like jQuery.PHPhtmlParser는 jQuery와 같은 임의의 css 셀렉터를 사용하여 태그를 선택할 수 있는 단순하고 유연한 HTML 파서입니다. The goal is to assiste in the development of tools which require a quick, easy way to scrape html, whether it’s valid or not!목표는 html의 유효 여부를 불문하고 빠르고 쉬운 스크래핑 방법을 필요로 하는 툴 개발을 지원하는 것입니다. This project was original supported by sunra/php-simple-html-dom-parser but the support seems to have stopped so this project is my adaptation of his previous work.이 프로젝트는 원래 sunra/php-simple-html-dom-parser에 의해 지원되었지만 지원이 중단된 것 같아 그의 전작을 각색한 프로젝트입니다.
Again, I would not recommend this parser.다시 말씀드리지만 이 파서는 추천하지 않습니다. It is rather slow with high CPU usage.CPU 사용률이 높기 때문에 다소 느립니다. There is also no function to clear memory of created DOM objects.작성된 DOM 객체의 메모리를 클리어하는 기능도 없습니다. These problems scale particularly with nested loops.이러한 문제는 특히 중첩된 루프에 의해 확대됩니다. The documentation itself is inaccurate and misspelled, with no responses to fixes since 14 Apr 16.문서 자체는 부정확하고 철자가 틀려 4월 16일 이후 수정에 대한 응답이 없습니다.
HTML 5HTML 5
You can use the above for parsing HTML5, but there can be quirks due to the markup HTML5 allows.HTML5의 해석에는 위의 내용을 사용할 수 있지만 HTML5가 허용하는 마크업으로 인해 기호가 발생할 수 있습니다. So for HTML5 you may want to consider using a dedicated parser.따라서 HTML5의 경우 전용 파서를 사용하는 것이 좋습니다. Note that these are written in PHP, so suffer from slower performance and increased memory usage compared to a compiled extension in a lower-level language.이것들은 PHP로 쓰여져 있기 때문에, 낮은 레벨의 언어로 컴파일 된 확장자에 비해, 퍼포먼스가 저하해, 메모리 사용량이 증가하는 것에 주의해 주세요.
HTML5DomDocumentHTML5Dom 문서
HTML5DOMDocument extends the native DOMDocument library.HTML5DOMDocument는 네이티브 DOMDocument 라이브러리를 확장합니다. It fixes some bugs and adds some new functionality.몇 가지 버그를 수정하고 새로운 기능을 추가합니다.
- Preserves html entities (DOMDocument does not)html 엔티티 유지(DOMDocument는 유지하지 않음)
- Preserves void tags (DOMDocument does not)보이드 태그 유지(DOMDocument는 유지하지 않음)
- Allows inserting HTML code that moves the correct parts to their proper places (head elements are inserted in the head, body elements in the body)올바른 부품을 올바른 위치로 이동하는 HTML 코드를 삽입할 수 있습니다(헤드 요소는 머리에 삽입하고 바디 요소는 몸에 삽입).
- Allows querying the DOM with CSS selectors (currently available: CSS 셀렉터를 사용하여 DOM을 조회할 수 있습니다(현재 사용 가능:
*
, ,tagname
, ,tagname#id
, ,#id
, ,tagname.classname
, ,.classname
, ,tagname.classname.classname2
, ,.classname.classname2
, ,tagname[attribute-selector]
, ,[attribute-selector]
, ,div, p
, ,div p
, ,div > p
, ,div + p
, and ,그리고.p ~ ul
.).)- Adds support for element->classList.element-> class List 지원을 추가합니다.
- Adds support for element->inner요소 -> 내부 지원을 추가합니다.HTML.HTML.
- Adds support for element->outer요소 ->외부 지원을 추가합니다.HTML.HTML.
HTML5HTML5
HTML5 is a standards-compliant HTML5 parser and writer written entirely in PHP.HTML5는 표준 준거 HTML5 파서이며 PHP로 작성되어 있습니다. It is stable and used in many production websites, and has well over five million downloads.안정적이고 많은 제작 웹사이트에서 사용되고 있으며 다운로드 수가 5백만 건을 훨씬 넘습니다.
HTML5 provides the following features.HTML5는 다음과 같은 기능을 제공합니다.
- An HTML5 serializerHTML5 시리얼라이저
- Support for PHP namespacesPHP 네임스페이스 지원
- Composer supportComposer 지원
- Event-based (SAX-like) parser이벤트 기반(SAX 유사) 파서
- A DOM tree builderDOM 트리 빌더
- Interoperability with QueryPathQuery Path와의 상호 운용성
- Runs on PHP 5.3.0 or newerPHP 5.3.0 이상에서 실행
Regular Expressions정규 표현
Last and least recommended, you can extract data from HTML with regular expressions.마지막으로 HTML에서 정규 표현을 사용하여 데이터를 추출할 수 있습니다. In general using Regular Expressions on HTML is discouraged.일반적으로 HTML에서 정규 표현을 사용하는 것은 권장되지 않습니다.
Most of the snippets you will find on the web to match markup are brittle.마크업과 일치하는 웹 조각은 대부분 깨지기 쉽습니다. In most cases they are only working for a very particular piece of HTML. Tiny markup changes, like adding whitespace somewhere, or adding, or changing attributes in a tag, can make the RegEx fails when it’s not properly written.대부분의 경우 이들은 HTML의 특정 부분에서만 작동합니다. 어딘가에 공백을 추가하거나 태그에서 속성을 추가하거나 변경하는 등의 작은 마크업 변경은 RegEx가 올바르게 작성되지 않을 때 실패할 수 있습니다. You should know what you are doing before using RegEx on HTML.HTML에서 RegEx를 사용하기 전에 무엇을 하고 있는지 알아야 합니다.
HTML parsers already know the syntactical rules of HTML. Regular expressions have to be taught for each new RegEx you write.HTML 파서는 HTML의 구문 규칙을 이미 알고 있습니다. 정규 표현은 새로 쓰는 RegEx마다 가르쳐야 합니다. RegEx are fine in some cases, but it really depends on your use-case.RegEx는 경우에 따라 다르지만 실제로 사용 사례에 따라 달라집니다.
You can write more reliable parsers, but writing a complete and reliable custom parser with regular expressions is a waste of time when the aforementioned libraries already exist and do a much better job on this.보다 신뢰할 수 있는 파서를 쓸 수 있지만, 정규 표현식을 사용하여 완전하고 신뢰할 수 있는 커스텀 파서를 쓰는 것은 앞서 말한 라이브러리가 이미 존재하고 이 문제를 훨씬 더 잘 처리할 수 있는 시간 낭비입니다.
Also see Parsing Html The Cthulhu Way‘Html Cthulhu Way 구문 분석’도 참조하십시오.
Books책들
If you want to spend some money, have a look at돈을 좀 쓰고 싶다면, 한번 보세요.
I am not affiliated with PHP Architect or the authors.저는 PHP 아키텍트나 저자와 관련이 없습니다.
Try Simple HTML DOM Parser.Simple HTML DOM 파서를 사용해 보십시오.
- A HTML DOM parser written in PHP 5+ that lets you manipulate HTML in a very easy way!HTML을 매우 쉽게 조작할 수 있는 PHP 5+로 작성된 HTML DOM 파서!
- Require PHP 5+.PHP 5+가 필요합니다.
- Supports invalid HTML.유효하지 않은 HTML을 지원합니다.
- Find tags on an HTML page with selectors just like jQuery.jQuery와 마찬가지로 선택기가 있는 HTML 페이지에서 태그를 찾습니다.
- Extract contents from HTML in a single line.HTML에서 콘텐츠를 한 줄로 추출합니다.
- Download다운로드.
Note: as the name suggests, it can be useful for simple tasks.주의: 이름에서 알 수 있듯이 간단한 작업에 유용합니다. It uses regular expressions instead of an HTML parser, so will be considerably slower for more complex tasks.HTML 파서 대신 정규 표현을 사용하기 때문에 더 복잡한 작업에서는 속도가 상당히 느려집니다. The bulk of its codebase was written in 2008, with only small improvements made since then.코드베이스의 대부분은 2008년에 작성되었으며, 그 이후 약간의 개선만 이루어졌을 뿐입니다. It does not follow modern PHP coding standards and would be challenging to incorporate into a modern PSR-compliant project.이것은 현대의 PHP 코딩 표준을 따르지 않기 때문에 현대의 PSR 준거 프로젝트에 통합하는 것은 어려울 것입니다.
Examples:예:
How to get HTML elements:HTML 요소를 가져오는 방법:
// Create DOM from URL or file $html = file_get_html('http://www.example.com/'); // Find all images foreach($html->find('img') as $element) echo $element->src . '<br>'; // Find all links foreach($html->find('a') as $element) echo $element->href . '<br>';
How to modify HTML elements:HTML 요소 수정 방법:
// Create DOM from string $html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>'); $html->find('div', 1)->class = 'bar'; $html->find('div[id=hello]', 0)->innertext = 'foo'; echo $html;
Extract content from HTML:HTML에서 콘텐츠 추출:
// Dump contents (without tags) from HTML echo file_get_html('http://www.google.com/')->plaintext;
Scraping Slashdot:슬래시닷 스크래핑:
// Create DOM from URL $html = file_get_html('http://slashdot.org/'); // Find all article blocks foreach($html->find('div.article') as $article) { $item['title'] = $article->find('div.title', 0)->plaintext; $item['intro'] = $article->find('div.intro', 0)->plaintext; $item['details'] = $article->find('div.details', 0)->plaintext; $articles[] = $item; } print_r($articles);
Just use DOMDocument->loadDOMDocument-> load를 사용합니다.HTML() and be done with it. libxml’s HTML parsing algorithm is quite good and fast, and contrary to popular belief, does not choke on malformed HTML.HTML() 및 be done it.libxml의 HTML 해석 알고리즘은 매우 좋고 빠릅니다.일반적인 생각과는 달리 부정한 형식의 HTML에서는 초크하지 않습니다.
Why you shouldn’t and when you should use regular expressions?왜 안 되고 언제 정규 표현을 써야 하죠?
First off, a common misnomer:먼저, 일반적인 오칭입니다. Regexps are not for “parsing“ HTML. Regexes can however “extract“ data.정규식은 HTML을 “파싱“하기 위한 것이 아닙니다. 그러나 정규식은 데이터를 “추출“할 수 있습니다. Extracting is what they’re made for.추출은 그들이 원하는 것이다. The major drawback of regex HTML extraction over proper SGML toolkits or baseline XML parsers are their syntactic effort and varying reliability.적절한 SGML 툴킷 또는 베이스라인 XML 파서에 대한 regex HTML 추출의 주요 단점은 구문적인 노력과 다양한 신뢰성입니다.
Consider that making a somewhat dependable HTML extraction regex:다소 신뢰할 수 있는 HTML 추출 regex를 만드는 것을 고려하십시오.
<as+class="?playbuttond?[^>]+id="(d+)".+? <as+class="[ws]*title [ws]*"[^>]+href="(http://[^">]+)"[^>]*>([^<>]+)</a>.+?
is way less readable than a simple phpQuery or QueryPath equivalent:단순한 phpQuery 또는 QueryPath에 비해 읽기 어렵습니다.
$div->find(".stationcool a")->attr("title");
There are however specific use cases where they can help.그러나 도움이 될 수 있는 구체적인 사용 사례가 있습니다.
- Many DOM traversal frontends don’t reveal HTML comments 많은 DOM 트래버설프런트 엔드에서는 HTML 코멘트가 표시되지 않습니다.
<!--
, which however are sometimes the more useful anchors for extraction.그러나 때로는 추출에 더 유용한 앵커이기도 합니다. In particular pseudo-HTML variations 특히 의사-HTML 변형<$var>
or SGML residues are easy to tame with regexps.또는 SGML 잔류물은 regexps로 길들이기 쉽다. - Oftentimes regular expressions can save post-processing.대부분의 경우 정규 표현식은 사후 처리를 저장할 수 있습니다. However HTML entities often require manual caretaking.그러나 HTML 엔티티는 수동 관리가 필요한 경우가 많습니다.
- And lastly, for extremely simple tasks like extracting <img src= urls, they are in fact a probable tool.마지막으로 <img src= url> 추출과 같은 매우 간단한 작업의 경우 실제로 툴이 될 수 있습니다. The speed advantage over SGML/XML parsers mostly just comes to play for these very basic extraction procedures.SGML/XML 파서보다 빠른 속도는 이러한 기본적인 추출 절차에서 주로 발휘됩니다.
It’s sometimes even advisable to pre-extract a snippet of HTML using regular expressions 정규 표현을 사용하여 HTML의 일부를 미리 추출하는 것이 좋습니다./<!--CONTENT-->(.+?)<!--END-->/
and process the remainder using the simpler HTML parser frontends.나머지는 간단한 HTML 파서 프런트엔드를 사용하여 처리합니다.
Note: I actually have this app, where I employ XML parsing and regular expressions alternatively.주의: 실제로 XML 구문 분석과 정규 표현을 번갈아 사용하는 앱이 있습니다. Just last week the PyQuery parsing broke, and the regex still worked.바로 지난주에 PyQuery 파싱이 중단되었고 regex는 여전히 작동했습니다. Yes weird, and I can’t explain it myself.네, 이상해요, 저도 설명할 수 없어요. But so it happened.하지만 그렇게 됐어.
So please don’t vote real-world considerations down, just because it doesn’t match the regex=evil meme.따라서 regex=devil meme와 일치하지 않는다고 해서 실제 고려 사항을 부정하지 마십시오. But let’s also not vote this up too much.하지만 이것 또한 너무 많이 투표하지는 말자. It’s just a sidenote for this topic. 이것은 이 주제에 대한 편파적인 표현일 뿐이다.
Note, this answer recommends libraries that have now been abandoned for 10+ years.참고로 이 답변은 현재 10년 이상 방치된 라이브러리를 권장합니다.
phpQuery and QueryPath are extremely similar in replicating the fluent jQuery API.phpQuery와 QueryPath는 fluent jQuery API 복제에서 매우 유사합니다. That’s also why they’re two of the easiest approaches to properly parse HTML in PHP.이것이 바로 PHP에서 HTML을 적절히 해석하기 위한 가장 쉬운 접근법 중 두 가지 이유입니다.
Examples for QueryPathQuery Path 예시
Basically you first create a queryable DOM tree from an HTML string:기본적으로 먼저 HTML 문자열에서 쿼리 가능한 DOM 트리를 만듭니다.
$qp = qp("<html><body><h1>title</h1>..."); // or give filename or URL
The resulting object contains a complete tree representation of the HTML document.결과 오브젝트에는 HTML 문서의 완전한 트리 표현이 포함됩니다. It can be traversed using DOM methods.DOM 메서드를 사용하여 통과할 수 있습니다. But the common approach is to use CSS selectors like in jQuery:단, 일반적인 접근법은 jQuery와 같이 CSS 셀렉터를 사용하는 것입니다.
$qp->find("div.classname")->children()->...; foreach ($qp->find("p img") as $img) { print qp($img)->attr("src"); }
Mostly you want to use simple 대부분 심플하게 사용하고 싶다#id
and 그리고..class
or 또는DIV
tag selectors for 태그 실렉터 태그 지정->find()
. But you can also use XPath statements, which sometimes are faster.그러나 XPath 문을 사용할 수도 있습니다.이것이 더 빠를 수 있습니다. Also typical jQuery methods like 또한 일반적인 jQuery 메서드는 다음과 같습니다.->children()
and 그리고.->text()
and particularly 특히->attr()
simplify extracting the right HTML snippets. (And already have their SGML entities decoded.)올바른 HTML 스니펫 추출을 단순화합니다(또한 해당 SGML 엔티티가 이미 디코딩되어 있습니다).
$qp->xpath("//div/p[1]"); // get first paragraph in a div
QueryPath also allows injecting new tags into the stream (QueryPath에서는 스트림에 새로운 태그를 삽입할 수도 있습니다(->append
), and later output and prettify an updated document (나중에 업데이트된 문서를 출력하고 예쁘게 만듭니다( ).->writeHTML
). It can not only parse malformed HTML, but also various XML dialects (with namespaces), and even extract data from HTML microformats (XFN, vCard).부정한 형식의 HTML뿐만 아니라 다양한 XML 방언(네임스페이스 포함), HTML 마이크로포맷(XFN, vCard)에서 데이터를 추출할 수도 있습니다.
$qp->find("a[target=_blank]")->toggleClass("usability-blunder");
..
phpQuery or QueryPath?phpQuery 또는 QueryPath?
Generally QueryPath is better suited for manipulation of documents.일반적으로 문서 조작에는 QueryPath가 적합합니다. While phpQuery also implements some pseudo AJAX methods (just HTTP requests) to more closely resemble jQuery.phpQuery는 jQuery와 매우 유사한 의사 AJAX 메서드(HTTP 요청만)도 구현합니다. It is said that phpQuery is often faster than QueryPath (because of fewer overall features).phpQuery가 QueryPath보다 빠른 경우가 많다고 합니다(전체 기능이 적기 때문입니다).
For further information on the differences see this comparison on the wayback machine from tagbyte.org. (Original source went missing, so here’s an internet archive link.차이점에 대한 자세한 내용은 tagbyte.org에서 반환되는 머신의 비교를 참조하십시오.(원래 소스가 없어졌습니다.여기 인터넷 아카이브 링크가 있습니다. Yes, you can still locate missing pages, people.)네, 아직 누락된 페이지를 찾을 수 있습니다.
Advantages이점
- Simplicity and Reliability심플함과 신뢰성
- Simple to use alternatives 사용하기 쉬운 대체 수단
->find("a img, a object, div a")
- Proper data unescaping (in comparison to regular expression grepping)적절한 데이터 이스케이프 없음(정규 표현 그리핑과 비교)