2011-09-11 109 views
1

我有一块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但不能使我满意。我错过了什么吗?

回答

2

我有同样的问题,得到了上述同样的答案。因为我不知道如何定义一个DTD我得到了以下解决方案:

更改HTML代码:

<section id="content" /> 

<section xml:id="content" /> 

如果您仍需要id属性apear (用于Javascript的目的),你可以使用下面的代码:

<section id="content" xml:id="content" /> 

我跑到另一个问题与吨他的解决方案,因为xml:id属性不会通过验证器。 我对这个问题的解决方案如下:保留HTML代码是:

<section id="content" /> 

现在改变这样的PHP代码:

/* ... 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'); 

这种解决方案非常适合我。我希望你也能找到它:)

相关问题