Why getElementById doesn't work in this case?
I have piece of PHP code.
PHP:
$Implementation = new DOMImplementation();
$Document = $Implementation->createDocument( NULL, NULL, $Implementation->createDocumentType( 'html' ) );
$Document->encoding = 'utf-8';
$Document->loadXML( $main_html[ 'main' ] ); // load main.html
$Document->xinclude();
$Fragment = $Document->createDocumentFragment();
$Fragment->appendXML( $main_html[ 'page' ] ); // load page.html
$D开发者_StackOverflow社区ocument->getElementById( 'content' )->appendChild( $Fragment );
...
Everything works well except last line, appears error:
PHP Fatal error: Call to a member function appendChild() on a non-object
It seems getElementById()
method doesn't work for $Document
.
Look at the HTML.
HTML (main.html):
...
</head>
<body xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="wrapper.html" />
</body>
</html>
HTML (wrapper.html):
<section
id="wrapper"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="header.html" />
<xi:include href="nav.html" />
<xi:include href="content.html" />
<xi:include href="aside.html" />
<xi:include href="footer.html" />
</section>
HTML (content.html):
<section id="content" />
I added $Document->validateOnParse = TRUE;
before $Document->loadXML( $main_html[ 'main' ] );
and tested without XInclude, but doesn`t work.
Finally I found the solution, bad line replace with:
$Document->getElementsByTagName( 'section' )->item( 1 )->appendChild( $Fragment );
getElementsByTagName()
method works for $Document
but doesn't satisfy me. Did I missed something?
I had the same problem and got the same answer mentioned above. Since I don't know how to define a DTD I got the following solution:
Change the HTML code:
<section id="content" />
into
<section xml:id="content" />
If you still need the id attribute to apear (for Javascript purposes) you can use the following code:
<section id="content" xml:id="content" />
I ran into another problem with this solution since xml:id attribute won't pass validator. My solution for this problem was as follows: Leave the HTML code as is:
<section id="content" />
Now change your PHP code like this:
/* ... Add xml:id tags */
$tags = $Document -> getElementsByTagName('*');
foreach ($tags as $tag)
$tag->setAttribute('xml:id',$tag->getAttribute('id'));
/* ... Here comes your PHP code */
$Document->getElementById( 'content' )->appendChild( $Fragment );
/* ... Remove xml:id tags */
foreach ($tags as $tag)
$tag->removeAttribute('xml:id');
This solution works perfect for me. I hope you find it useful as well :)
You have to pass a DTD which defines the id
attribute. Otherwise, you cannot use getElementById
.
For more information, see:
- http://nl.php.net/manual/en/domimplementation.createdocumenttype.php
- http://www.php.net/manual/en/domdocument.getelementbyid.php
精彩评论