php - DOMDocument::getElementById 返回 NULL

标签 php dom

<分区>

Possible Duplicate:
Simplify PHP DOM XML parsing - how?

这是我的 XML (c.xml):

<?xml version="1.0" encoding="utf-8"?>
<root>
    <head>
        <title id="title">Hello</title>
    </head>
</root>

我的工作:

$dom = new DOMDocument;

$dom->load('./c.xml');

var_dump($dom->getElementById('title'));die(); // returns NULL

这里有什么问题&?

UPD

$dom->validate(); 返回 DOMDocument::validate(): no DTD found!

最佳答案

我认为The Manual解释为什么会发生这种情况

For this function to work, you will need either to set some ID attributes with DOMElement->setIdAttribute() or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document with DOMDocument->validate() or DOMDocument->validateOnParse before using this function.

可能的修复:

  1. 调用$dom->validate();,之后你可以使用$dom->getElementById(),不管出于某种原因的错误。
  2. 如果您不想验证,请使用 XPath:

    $x = new DOMXPath($dom);

    $el = $x->query("//*[@id='title']")->item(0);//寻找id=title

使用自定义 DTD 的示例:

$dtd = '<!ELEMENT note (to,from,heading,body)>
        <!ELEMENT to (#PCDATA)>
        <!ELEMENT from (#PCDATA)>
        <!ELEMENT heading (#PCDATA)>
        <!ELEMENT body (#PCDATA)>';

$systemId = 'data://text/plain;base64,'.base64_encode($dtd);

$creator = new DOMImplementation;
$doctype = $creator->createDocumentType($root, null, $systemId); //Based on your DTD from above

关于php - DOMDocument::getElementById 返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12298833/

相关文章:

php - 电子邮件转发器无法连接 mySQL 数据库

php - CakePHP 单选按钮

javascript - 具有相同id的多个div中的Ajax json值

javascript - 在 JavaScript 中动态删除行

javascript - 对闭包内创建的事件调用闭包函数

javascript - PHP 相当于 JavaScript 的parentNode 属性

javascript - 动态路由 PHP 和 AngularJS

php - 诊断 "The connection to localhost was interrupted"

jQuery 相当于 createElement?

javascript - 单击 svg 元素时应用焦点 css