【发布时间】:2017-04-07 05:53:09
【问题描述】:
我是 PHP 库 phpQuery 内容解析器的忠实粉丝(因为它很像 jQuery,同时使用 PHP DOMDocument 提取标记)但我注意到了一个错误快速关闭事件<img />而不是<div></div>的特定元素
我注意到这个错误也出现在 DOMDocument 和 phpQuery 中。
我写了一个简单的类PhpContentDocument来转储一个简单的html文档。
require_once "../phpquery_lib/phpQuery.php";
require_once "PhpContentDocument.class.php";
$sample_document = new PhpContentDocument('Sample Document');
$sample_document->addElement('text element', "<span class='text_element'>This is some Sample Text</span>");
$sample_document->addElement('image element', "<img src='png_file.png' alt='png_file' id='png_file' />");
$sample_document_string = $sample_document->get_string();
结果如你所愿......
<!DOCTYPE HTML>
<html>
<head>
<title>Sample Document</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<body>
<span class='text_element'>This is some Sample Text</span>
<img src='png_file.png' alt='png_file' id='png_file' />
</body>
</html>
但是当使用 saveHTML 调用文档时
$php_query_document = new DOMDocument('UTF-8', '1.0');
$php_query_document->formatOutput = true;
$php_query_document->preserveWhiteSpace = true;
$php_query_document->loadHTML($sample_document_string);
$php_query_document_string = $php_query_document->saveHTML();
echo $php_query_document_string;
它返回...
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Sample Document</title>
</head>
<body>
<span class="text_element">This is some Sample Text</span>
<img src="png_file.png" alt="png_file" id="png_file">
</body>
</html>
我遇到的主要问题是,当我在元素 img#png_file 上使用 SimpleXMLElement 时 (例如)
使用内容解析器将<img src="png_file.png" alt="png_file" id="png_file"> 作为参数传递
$simple_doc = new SimpleXMLElement((string) $php_query_document->find('img#png_file'));
我收到以下警告和异常,即使我的原始标记可以使用 SimpleXMLElement。
Warning: SimpleXMLElement::__construct(): Entity: line 1: parser error : Premature end of data in tag img line 1 in F:\xampp\htdocs\Test_Code\phpquery_test_items\index.php on line 17
Warning: SimpleXMLElement::__construct(): <img src="png_file.png" alt="png_file" id="png_file"> in F:\xampp\htdocs\Test_Code\phpquery_test_items\index.php on line 17
Warning: SimpleXMLElement::__construct(): ^ in F:\xampp\htdocs\Test_Code\phpquery_test_items\index.php on line 17
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in F:\xampp\htdocs\Test_Code\phpquery_test_items\index.php:17 Stack trace: #0 F:\xampp\htdocs\Test_Code\phpquery_test_items\index.php(17): SimpleXMLElement->__construct('<img src="png_f...') #1 {main} thrown in F:\xampp\htdocs\Test_Code\phpquery_test_items\index.php on line 17
由于元素没有closing event。
TL:DR Warning: SimpleXMLElement::__construct(): Entity: line 1: parser error : Premature end of data in tag img line 1
我该如何解决这个问题?我确实有一些想法,但最好是
- 我想要一个解决方案,我可以使用正则表达式(我知道 ELEMENT TYPE)将
/>替换为<{element_type}/>,反之亦然。 -
固定
saveHTML的DOMDocument类(可能是为了继承其他功能而扩展DOMDocument的类)。
【问题讨论】:
标签: html simplexml domdocument w3c-validation phpquery