使用PHP在特定节点之前更新XML插入节点

时间:2013-02-16 12:30:12

标签: xml domdocument php

我有一个显示客户端徽标的XML,并希望通过PHP面板添加徽标。当前的XML代码是:          

    <item>
        <image><![CDATA[images/clients_5.gif]]></image>
    </item>
    <item>
        <image><![CDATA[images/clients_6.gif]]></image>
    </item>
    <item>
        <image><![CDATA[images/clients_7.gif]]></image>
    </item>
    <item>
        <image><![CDATA[images/clients_8.gif]]></image>
    </item>
    <item>
        <image><![CDATA[images/clients_9.gif]]></image>
    </item>
    <item>
        <image><![CDATA[images/clients_10.gif]]></image>
    </item>
    <item>
        <image><![CDATA[images/clients_11.gif]]></image>
    </item>
    <item>
        <image><![CDATA[images/clients_12.gif]]></image>
    </item>
    <item>
        <image><![CDATA[images/clients_13.gif]]></image>
    </item>
    <item>
        <image><![CDATA[images/clients_14.gif]]></image>
    </item>
    <item>
        <image><![CDATA[images/clients_15.gif]]></image>
    </item>

    <footer><![CDATA[copyright evolve entertainment and marketing solutions, 2009]]></footer>

</clients>

PHP代码是:

if(!empty($_FILES["logo"]["name"]))
{
    $handle = new Upload($_FILES["logo"]);  
    $imgId = uniqid();      
    if ($handle->uploaded) 
    {
        $handle->file_name_body_pre =   $imgId;
        $handle->image_resize            = false;
        $handle->Process(ROOT_PATH.'images/');
        $handle->processed;
    }
    $imgName = $imgId.$_FILES["logo"]['name'];

    $parent_path = "//main";
    $next_path = "//main/clients/footer"; 
    $xpath = new DomXPath($doc); 
    $parent = $xpath->query($parent_path); 
    $next = $xpath->query($next_path);



    $imageNode = $doc->createElement('image');
    $cdata=$doc->createCDATASection($imgName);
    $imageNode = $imageNode->appendChild($cdata);

    //$parent->item(0)->insertBefore($imageNode, $next->item(0)); 

    $section = $doc->insertBefore($imageNode,$next->item(0));

    $doc->save(XML_PATH.'clients.xml');

我希望在页脚之前添加新节点或在子节点中添加新节点。当我尝试上面的代码时,它会发出以下错误:未捕获的异常'DOMException',消息'找不到错误'

1 个答案:

答案 0 :(得分:0)

  

未捕获的异常'DOMException',消息'Not Found Error'

这意味着找不到节点。您没有指定该行,但我认为它是:

$section = $doc->insertBefore($imageNode, $next->item(0));

这是有问题的。 $doc是根元素,但它不是$next->item(0)的父元素。要使其正常工作, refnode (此处为$next->item(0))必须是$doc的孩子 - 但事实并非如此。

相反,这是一个简单而广泛的例子,它也提供了一些更好的代码:

$refnode = $next->item(0);
$parent  = $refnode->parentNode;
$section = $parent->insertBefore($imageNode, $refnode);

当然你不需要使用那么多变量,但是这个例子应该引导你前进,特别是看$refnode->parentNode来获取正确的节点,然后在它的任何子节点之前插入它。

是的,这是错误的:

$imageNode = $imageNode->appendChild($cdata);

对于您使用的所有功能,您应该再次检查手册。只是为了确保您知道这些函数返回的内容。

相关问题