【问题标题】:Call to undefined method DOMDocument::createDocumentType()调用未定义的方法 DOMDocument::createDocumentType()
【发布时间】:2013-04-09 03:37:45
【问题描述】:

我有以下脚本 sn-p。最初我没有意识到使用 getElementById 需要包含 createDocumentType,但现在我得到了上面列出的错误。我在这里做错了什么?提前致谢!

...
$result = curl_exec($ch); //contains some webpage i am grabbing remotely

$dom = new DOMDocument();
$dom->createDocumentType('html', '-//W3C//DTD HTML 4.01 Transitional//EN', 'http://www.w3.org/TR/html4/loose.dtd');
$elements = $dom->loadHTML($result);
$e = $elements->getElementById('1');
...

编辑:附加说明,我在远程页面上验证了 DOM 是正确的。

【问题讨论】:

  • 我从来不用createDocumentType。你确定getElementById() 没有它就不能工作吗?此外,从技术上讲,不允许以数字开头的 id。
  • 嗯,没有DOMDocument::createDocumentType 这样的东西。你从哪里得到的想法?

标签: php curl domdocument


【解决方案1】:

DOMDocument 没有名为createDocumentType 的方法,如您在Manual 中所见。该方法属于DOMImplemetation class。它是这样使用的(摘自手册):

// Creates an instance of the DOMImplementation class
$imp = new DOMImplementation;

// Creates a DOMDocumentType instance
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Creates a DOMDocument instance
$dom = $imp->createDocument("", "", $dtd);

由于您想将 HTML 加载到文档中,因此无需指定文档类型,因为它是根据导入的 HTML 确定的。您只需要拥有一些id 属性,或将其他属性标识为id 的DTD。这是 HTML 文件的一部分,而不是解析 PHP 代码。

$dom = new DOMDocument();
$dom->loadHTML($result);
$element = $dom->getElementById('my_id');

会做的。

【讨论】:

  • 好吧,我最初使用的是 $dom = new DOMDocument();紧随其后的是 getElementById。我从搜索中不明白的是如何指定我不控制内容的网页的 id 属性?您能否提供一个使用我的 sn-p 但减去 createDocumentType 的示例?与此同时,我会尝试你的方式。我最初在 getELementById 上遇到致命错误,搜索导致我找到了当前的解决方案...
  • 哇好。这就是我在上面那个古怪的版本之前的原始代码。不过,我收到了一堆错误和警告。使用您的版本(我的原始版本),解决方案就像 @$dom->loadHTML($result);消除错误。
  • 感谢您的解释,让我回到第一方。 :-)
猜你喜欢
  • 1970-01-01
  • 2016-01-31
  • 2014-07-20
  • 2012-07-27
  • 2019-10-25
  • 2018-07-11
  • 2013-10-23
  • 2012-02-17
相关资源
最近更新 更多