2

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!

Community
  • 1
  • 1
s.webbandit
  • 15,742
  • 14
  • 56
  • 80

1 Answers1

11

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:

  1. Call $dom->validate();, afterwards you can use $dom->getElementById(), regardless of the errors for some reason.
  2. 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
Leigh
  • 12,801
  • 3
  • 38
  • 60
Pez Cuckow
  • 13,592
  • 15
  • 77
  • 127