如何在PHP中解析和处理HTML/XML?
如何解析HTML/XML并从中提取信息?是相当稳定的,即使不再维护它。另一种选择是通过管道传输HTML,然后使用标准XML工具对其进行解析。相当稳定,即使不再维护它。另一种选择是通过管道传递HTML,然后使用标准XML工具对其进行解析。简单HTML DOM是一种很棒的开源解析器: 它以面向对象的方式处理DOM元素,新的迭代覆盖了大量不兼容的代码。还有一些很棒的函数,如JavaScript中的“find”函数,它将返回该标记名元素的所有实例如何在PHP中解析和处理HTML/XML?,php,xml,parsing,xml-parsing,html-parsing,Php,Xml,Parsing,Xml Parsing,Html Parsing,如何解析HTML/XML并从中提取信息?是相当稳定的,即使不再维护它。另一种选择是通过管道传输HTML,然后使用标准XML工具对其进行解析。相当稳定,即使不再维护它。另一种选择是通过管道传递HTML,然后使用标准XML工具对其进行解析。简单HTML DOM是一种很棒的开源解析器: 它以面向对象的方式处理DOM元素,新的迭代覆盖了大量不兼容的代码。还有一些很棒的函数,如JavaScript中的“find”函数,它将返回该标记名元素的所有实例 我已经在许多工具中使用过它,在许多不同类型的网页上测试
我已经在许多工具中使用过它,在许多不同类型的网页上测试过它,我认为它工作得很好。简单HTML DOM是一个很棒的开源解析器: 它以面向对象的方式处理DOM元素,新的迭代覆盖了大量不兼容的代码。还有一些很棒的函数,如JavaScript中的“find”函数,它将返回该标记名元素的所有实例
我已经在许多工具中使用过它,在许多不同类型的网页上测试过它,我认为它工作得很好。您可以尝试使用类似于清理任何“损坏的”HTML并将HTML转换为XHTML的东西,然后您可以使用XML解析器进行解析。您可以尝试使用类似于清理任何“损坏的”HTML的东西HTML并将HTML转换为XHTML,然后您可以使用XML解析器对其进行解析。只需使用它即可。libxml的HTML解析算法非常好且快速,而且与流行的观点相反,它不会被格式错误的HTML阻塞。只要使用它就可以了。libxml的HTML解析算法非常好且快速,而且与流行的观点相反,它不会被格式错误的HTML阻塞。试试看
- 一个用PHP5+编写的HTMLDOM解析器,可以让您以非常简单的方式操作HTML李>
- 需要PHP5+
- 支持无效的HTML
- 使用选择器在HTML页面上查找标记,就像jQuery一样
- 在一行中从HTML中提取内容
如何获取HTML元素:
刮削斜杠: 试一试
- 一个用PHP5+编写的HTMLDOM解析器,可以让您以非常简单的方式操作HTML李>
- 需要PHP5+
- 支持无效的HTML
- 使用选择器在HTML页面上查找标记,就像jQuery一样
- 在一行中从HTML中提取内容
如何获取HTML元素:
刮削斜杠: 本机XML扩展 我更喜欢使用其中的一个,因为它们与PHP捆绑在一起,通常比所有第三方lib都快,并提供了我需要的对标记的所有控制 DOM扩展允许您使用PHP5通过DOM API对XML文档进行操作。它是W3C文档对象模型核心级别3的实现,是一个平台和语言中立的界面,允许程序和脚本动态访问和更新文档的内容、结构和样式 DOM能够解析和修改真实世界(破碎的)HTML,它可以做到这一点。它是基于 使用DOM需要一些时间才能提高效率,但在我看来,这是非常值得的。因为DOM是一个与语言无关的接口,您可以在许多语言中找到实现,因此如果您需要更改编程语言,那么您可能已经知道如何使用该语言的DOM API 在中可以找到基本用法示例,在中可以找到一般概念概述 ,因此,如果您选择使用它,您可以确保您遇到的大多数问题都可以通过搜索/浏览堆栈溢出来解决 XMLReader扩展是一个XML拉式解析器。读卡器充当文档流上前进的光标,并在途中的每个节点处停止 与DOM一样,XMLReader也是基于libxml的。我不知道如何触发HTML解析器模块,因此使用XMLReader解析损坏的HTML可能不如使用DOM(在DOM中可以显式告诉它使用libxml的HTML解析器模块)健壮 有关基本用法示例,请访问 此扩展允许您创建XML解析器,然后为不同的XML事件定义处理程序。每个XML解析器也有一些可以调整的参数 XML解析器库也基于libxml,并实现了一个样式XML推式解析器。对于内存管理来说,它可能比DOM或SimpleXML更好,但与XMLReader实现的pull解析器相比,它更难使用 SimpleXML扩展提供了一个非常简单且易于使用的工具集,用于将XML转换为可以使用普通属性选择器和数组迭代器处理的对象 当您知道HTML是有效的XHTML时,SimpleXML是一个选项。如果需要解析损坏的HTML,不要考虑SimeXML,因为它会哽住。< /P> 基本用法示例可在中找到,并且有
第三方库(基于libxml) 如果您更喜欢使用第三方库,我建议使用实际使用/under的库,而不是字符串解析 - FluentDOM为PHP中的DOMDocument提供了类似于jQuery的FluentXML接口。选择器是用XPath或CSS编写的(使用CSS到XPath转换器)。当前版本扩展了DOM实现的标准接口,并添加了来自DOM生活标准的特性。FluentDOM可以加载JSON、CSV、JsonML、RabbitFish等格式。可以通过Composer安装 Wa72\HtmlPageDom`是一个易于操作HTML的PHP库 使用它的文档需要遍历 DOM树,并通过添加操作DOM的方法对其进行扩展 HTML文档树 (多年未更新) phpQuery是服务器端的chainab
// 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>';
// 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;
// Dump contents (without tags) from HTML
echo file_get_html('http://www.google.com/')->plaintext;
// 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);
Ability to manipulate elements and their attributes
Supports invalid HTML and UTF8
Can perform advanced CSS3-like queries on elements (like jQuery -- namespaces supported)
Minify CSS and Javascript
Sort attributes, change character case, correct indentation, etc.
Parsing documents using callbacks based on current character/token
Operations separated in smaller functions for easy overriding
<a\s+class="?playbutton\d?[^>]+id="(\d+)".+? <a\s+class="[\w\s]*title
[\w\s]*"[^>]+href="(http://[^">]+)"[^>]*>([^<>]+)</a>.+?
$div->find(".stationcool a")->attr("title");
$qp = qp("<html><body><h1>title</h1>..."); // or give filename or URL
$qp->find("div.classname")->children()->...;
foreach ($qp->find("p img") as $img) {
print qp($img)->attr("src");
}
$qp->xpath("//div/p[1]"); // get first paragraph in a div
$qp->find("a[target=_blank]")->toggleClass("usability-blunder");
$results = qp("div p");
$forename = $results->find("input[name='forename']");
$forename = $results->branch()->find("input[name='forname']")
foreach($html->find('img') as $element)
echo $element->src . '<br>';
$source = new XmlExtractor("path/to/tag", "/path/to/file.xml");
foreach ($source as $tag) {
echo $tag->field1;
echo $tag->field2->subfield1;
}
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
function array_combine_($keys, $values) {
$result = array();
foreach ($keys as $i => $k) {
$result[$k][] = $values[$i];
}
array_walk($result, create_function('&$v', '$v = (count($v) == 1)? array_pop($v): $v;'));
return $result;
}
function extract_data($str) {
return (is_array($str))
? array_map('extract_data', $str)
: ((!preg_match_all('#<([A-Za-z0-9_]*)[^>]*>(.*?)</\1>#s', $str, $matches))
? $str
: array_map(('extract_data'), array_combine_($matches[1], $matches[2])));
}
print_r(extract_data(file_get_contents("http://www.google.com/")));
namespace PowerTools;
use \Symfony\Component\CssSelector\CssSelector as CssSelector;
class DOM_Document extends \DOMDocument {
public function __construct($data = false, $doctype = 'html', $encoding = 'UTF-8', $version = '1.0') {
parent::__construct($version, $encoding);
if ($doctype && $doctype === 'html') {
@$this->loadHTML($data);
} else {
@$this->loadXML($data);
}
}
public function querySelectorAll($selector, $contextnode = null) {
if (isset($this->doctype->name) && $this->doctype->name == 'html') {
CssSelector::enableHtmlExtension();
} else {
CssSelector::disableHtmlExtension();
}
$xpath = new \DOMXpath($this);
return $xpath->query(CssSelector::toXPath($selector, 'descendant::'), $contextnode);
}
[...]
public function loadHTMLFile($filename, $options = 0) {
$this->loadHTML(file_get_contents($filename), $options);
}
public function loadHTML($source, $options = 0) {
if ($source && $source != '') {
$data = trim($source);
$html5 = new HTML5(array('targetDocument' => $this, 'disableHtmlNsInDom' => true));
$data_start = mb_substr($data, 0, 10);
if (strpos($data_start, '<!DOCTYPE ') === 0 || strpos($data_start, '<html>') === 0) {
$html5->loadHTML($data);
} else {
@$this->loadHTML('<!DOCTYPE html><html><head><meta charset="' . $encoding . '" /></head><body></body></html>');
$t = $html5->loadHTMLFragment($data);
$docbody = $this->getElementsByTagName('body')->item(0);
while ($t->hasChildNodes()) {
$docbody->appendChild($t->firstChild);
}
}
}
}
[...]
}
namespace PowerTools;
// Get file content
$htmlcode = file_get_contents('https://github.com');
// Define your DOMCrawler based on file string
$H = new DOM_Query($htmlcode);
// Define your DOMCrawler based on an existing DOM_Query instance
$H = new DOM_Query($H->select('body'));
// Passing a string (CSS selector)
$s = $H->select('div.foo');
// Passing an element object (DOM Element)
$s = $H->select($documentBody);
// Passing a DOM Query object
$s = $H->select( $H->select('p + p'));
// Select the body tag
$body = $H->select('body');
// Combine different classes as one selector to get all site blocks
$siteblocks = $body->select('.site-header, .masthead, .site-body, .site-footer');
// Nest your methods just like you would with jQuery
$siteblocks->select('button')->add('span')->addClass('icon icon-printer');
// Use a lambda function to set the text of all site blocks
$siteblocks->text(function( $i, $val) {
return $i . " - " . $val->attr('class');
});
// Append the following HTML to all site blocks
$siteblocks->append('<div class="site-center"></div>');
// Use a descendant selector to select the site's footer
$sitefooter = $body->select('.site-footer > .site-center');
// Set some attributes for the site's footer
$sitefooter->attr(array('id' => 'aweeesome', 'data-val' => 'see'));
// Use a lambda function to set the attributes of all site blocks
$siteblocks->attr('data-val', function( $i, $val) {
return $i . " - " . $val->attr('class') . " - photo by Kelly Clark";
});
// Select the parent of the site's footer
$sitefooterparent = $sitefooter->parent();
// Remove the class of all i-tags within the site's footer's parent
$sitefooterparent->select('i')->removeAttr('class');
// Wrap the site's footer within two nex selectors
$sitefooter->wrap('<section><div class="footer-wrapper"></div></section>');
[...]
$doc = fluidxml('<html>...</html>');
$title = $doc->query('//head/title')[0]->nodeValue;
$doc->query('//body/p', 'div.active', '#bgId')
->each(function($i, $node) {
// $node is a DOMNode.
$tag = $node->nodeName;
$text = $node->nodeValue;
$class = $node->getAttribute('class');
});
$dom = new IvoPetkov\HTML5DOMDocument();
$dom->loadHTML('<!DOCTYPE html><html><body><h1>Hello</h1><div class="content">This is some text</div></body></html>');
echo $dom->querySelector('h1')->innerHTML;
<pre><?php
include "ScarletsQuery.php";
// Load the HTML content and parse it
$html = file_get_contents('https://www.lipsum.com');
$dom = Scarlets\Library\MarkupLanguage::parseText($html);
// Select meta tag on the HTML header
$description = $dom->selector('head meta[name="description"]')[0];
// Get 'content' attribute value from meta tag
print_r($description->attr('content'));
$description = $dom->selector('#Content p');
// Get element array
print_r($description->view);
$xml='http://www.example.com/rss.xml';
$rss = simplexml_load_string($xml);
$i = 0;
foreach ($rss->channel->item as $feedItem) {
$i++;
echo $title=$feedItem->title;
echo '<br>';
echo $link=$feedItem->link;
echo '<br>';
if($feedItem->description !='') {
$des=$feedItem->description;
} else {
$des='';
}
echo $des;
echo '<br>';
if($i>5) break;
}