为什么getElementById在这种情况下不起作用? [英] Why getElementById doesn't work in this case?
问题描述
我有一些PHP代码。
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
$Document->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
似乎 getElementById()
方法不适用于 $ Document
。
It seems getElementById()
method doesn't work for $Document
.
查看HTML。
HTML(main.html):
HTML (main.html):
...
</head>
<body xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="wrapper.html" />
</body>
</html>
HTML(wrapper.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):
HTML (content.html):
<section id="content" />
我添加了 $ Document-> validateOnParse = TRUE;
before $ Document-> loadXML($ main_html ['main']);
并在没有XInclude的情况下测试,但没有工作。
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()
方法适用于 $ Document
但不满足我。我错过了什么吗?
getElementsByTagName()
method works for $Document
but doesn't satisfy me. Did I missed something?
推荐答案
你必须传递一个定义 id
属性。否则,您不能使用 getElementById
。
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
- http://nl.php.net/manual/en/domimplementation.createdocumenttype.php
- http://www.php.net/manual/en/domdocument.getelementbyid.php
这篇关于为什么getElementById在这种情况下不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!