Possible Duplicate:
Simplify PHP DOM XML parsing - how?
Here is my XML (c.xml):
<?xml version="1.0" encoding="utf-8"?>
<root>
<head>
<title id="title">Hello</title>
</head>
</root>
What I do:
$dom = new DOMDocument;
$dom->load('./c.xml');
var_dump($dom->getElementById('title'));die(); // returns NULL
What is the problem here&?
UPD
$dom->validate(); returns DOMDocument::validate(): no DTD found!
I think The Manual explains why this may happen
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.
Potential fixes:
$dom->validate();, afterwards you can use $dom->getElementById(), regardless of the errors for some reason.Use XPath if you don't feel like validating:
$x = new DOMXPath($dom);
$el = $x->query("//*[@id='title']")->item(0); //Look for id=title
Example of using a custom 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With