我希望能够加载任何html文档并使用php的domdocument功能对其进行编辑。
问题是,有些网站(例如facebook)会将XML样式的名称空间添加到其标签中。使用PHP DOMDocument难以解析脏的html代码
<fb:like send="true" width="450" show_faces="true"></fb:like>
DOMDocument对脏代码非常宽容,但它不会接受html代码中的namescpaces。什么情况是:
- 如果我使用loadHTML加载代码,名称空间将得到剥离出来,但我需要它留
- 如果我使用的loadXML加载代码,我会得到吨的错误是状态我没有加载有效的XML
所以我的想法是将我得到的html转换成XML,以便我可以使用loadXML解析它。我的问题是,我该如何做到这一点,我应该使用哪种工具(我听说过Tidy,但我无法让它工作),还是使用不同的解析器(一种可以处理html中的名称空间的解析器代码)
代码片段:
<?php
$html = file_get_contents($_POST['url']);
$domDoc = new DOMDocument();
$domDoc->loadHTML($html);
//Just do anything here. It doesn't matter what. For example I'm deleting the head tag
$headTag = $domDoc->getElementsByTagName("head")->item(0);
$headTagParent = $headTag->parentNode;
$headTagParent->removeChild($headTag);
echo $domDoc->saveHTML();
//This will work as expected for any url EXCEPT the ones that use XML namespaces like facebook does as described above. In case of such dirty coding the namespace will get deleted by DOMDocument
>
可能重复(http://stackoverflow.com/questions/30076922/convert-html-code-to-doc-using-php- [使用PHP和PHPWord转换HTML代码DOC]和-phpword) –
请编辑你的问题,并添加一个HTML/XML的最低范例。 – michi
@Varun Naharia我很抱歉,但这并没有帮助我。那对我的问题没有答案。 – Syndace