-1

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>

4

1 に答える 1

2

$entriesは配列ではなく、DOMNodeList オブジェクトです。で空かどうかを確認し$entries->length == 0ます。

于 2012-05-25T07:02:42.590 に答える