如何使用php将一些元素附加到xml中的特定元素?

时间:2012-05-25 06:59:33

标签: php xml arrays dom xpath

我正在尝试使用PHP在XML文件中附加一些数据。

我正在搜索一个单词,如果它已经存在于XML中。

如果它存在我只需要将数据附加到它,否则我必须创建整个元素。

为此我使用DOMXPath。代码如下:

$fname="ontology.xml";  

$xml=new DomDocument;
$xml->Load($fname);

$xpath = new DOMXPath($xml);

$query = '//RelatedTerms/words/word/word_title[.="'.$word.'"]';

$entries=$xpath->query($query);

 if($entries->length!=0)
{   
    foreach($entries as $entry)
    {
        $wordElement=$xml->getElementsByTagName($entry->parentNode->nodeName)->item(0);
//Problem is here even if the <word> is found at the second position it append the element to the first <word> element.

            $newIsaElement=$xml->createElement('isa');
            $newIsaTitleElement=$xml->createElement('isa_title',"sample");
            $newRelevanceTitle=$xml->createElement('relevance',"9");

            $newIsaElement->appendChild($newIsaTitleElement);
            $newIsaElement->appendChild($newRelevanceTitle);

            //$newIsaTitleElement->appendChild($newIsaElement);
            $wordElement->appendChild($newIsaElement);
            $xml->save($fname); 

    }
}
else
{
    echo "In Here!";        

    $words=$xml->getElementsByTagName('words')->item(0);
    $newWordElement=$xml->createElement('word');
    $newWordTitleElement=$xml->createElement('word_title',$word);
    $newIsaElement=$xml->createElement('isa');
    $newIsaTitleElement=$xml->createElement('isa_title',"test");
    $newRelevanceTitle=$xml->createElement('relevance',"2");

    $newWordElement->appendChild($newWordTitleElement);
    $newIsaElement->appendChild($newIsaTitleElement);
    $newIsaElement->appendChild($newRelevanceTitle);
    $newWordElement->appendChild($newIsaElement);

    $words->appendChild($newWordElement);

    $xml->save($fname);
}

我想将元素添加到找到单词的同一元素中。请帮我解决这个问题!

谢谢!

PS:如果需要,这是xml文件的格式!

<RelatedTerms>
<words>
    <word>
        <word_title>algo</word_title>
        <isa>
            <isa_title>algorithm</isa_title>
            <relevance>9</relevance>
        </isa>
        <hasa>
            <hasa_title>Algorithmic Example</hasa_title>
            <relevance>7</relevance>
        </hasa>
        <akindof>
            <akindof_title>Pseudo Code</akindof_title>
            <relevance>8</relevance>
        </akindof>
        <partof>
            <partof_title>Data Structures</partof_title>
            <relevance>9</relevance>
        </partof>
    </word>
            <word>
                   <word_title>algo</word_title>
                   <isa>
                      <isa_title>test</isa_title>
                       <relevance>9</relevance> //instead of adding it here it adds to the above element
                    </isa>
            </word>
</words>

1 个答案:

答案 0 :(得分:2)

$entries不是数组,它是DOMNodeList对象。使用$entries->length == 0检查是否为空。