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.
可能的修复:
- 调用
$dom->validate();
,之后你可以使用$dom->getElementById()
,不管出于某种原因的错误。
如果您不想验证,请使用 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