我有一块PHP代码。为什么getElementById在这种情况下不起作用?
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);
...
一切运作良好,除了最后一行,出现错误:
PHP Fatal error: Call to a member function appendChild() on a non-object
看来getElementById()
方法$Document
不起作用。
看看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" />
我之前加入$Document->validateOnParse = TRUE;
$Document->loadXML($main_html[ 'main' ]);
和测试没有XInclude,但没有工作。
最后我找到了解决办法,坏线替换为:
$Document->getElementsByTagName('section')->item(1)->appendChild($Fragment);
getElementsByTagName()
方法适用于$Document
但不能使我满意。我错过了什么吗?