2011-01-23 6 views
0

私は何時間もブラウズしてきましたが、新しい子要素をXMLファイルに挿入してXMLファイルを保存する方法の簡単な説明やデモンストレーションはありません。ここでPHPで新しい子XML要素を挿入するのに助けが必要

は、XMLツリーは、(非常に単純な)

<book> 

    <chapter> 
     <title>Everyday Italian</title> 
     <year>2005</year> 
    </chapter> 
    <chapter> 
     <title>Harry Potter</title> 
     <year>2005</year> 
    </chapter> 
    <chapter> 
     <title>XQuery Kick Start</title> 
     <year>2003</year> 
    </chapter> 

</book > 

... 私は深く、これと任意の助けをいただければ幸いです。..です。もう一度要約すると、私はPHPファイルを持っており、目標は特定の "title"と "year"の新しい "chapter"を挿入してから新しいファイルを保存することです(基本的にbook.xmlファイルを上書きします)。

答えて

1

あなたが必要とする http://php.net/manual/en/domdocument.save.php

方法:

  • DOMDocument->負荷()
    //ロードXMLからあなたが必要とするすべての情報を提供しますPHPマニュアル内の例がありますファイル
  • DOMDocument->のcreateElement()
    //要素ノードを作成
  • DOMDocument->はcreateTextNode()
    // textNode
  • DOMNode->のappendChild()
    を作成//別の
  • DOMDocument-に一つのノードを追加>ファイル
  • にXMLを保存//
    )(セーブ

<?php 
    //create a document 
    $doc=new DOMDocument; 
    //load the file 
    $doc->load('book.xml'); 
    //create chapter-element 
    $chapter=$doc->createElement('chapter'); 
    //create title-element 
    $title=$doc->createElement('title'); 
    //insert text to the title 
    $title->appendChild($doc->createTextNode('new title for a new chapter')); 
    //create year-element 
    $year=$doc->createElement('year'); 
    //insert text to the year 
    $year->appendChild($doc->createTextNode('new year for a new chapter')); 
    //append title and year to the chapter 
    $chapter->appendChild($title); 
    $chapter->appendChild($year); 
    //append the chapter to the root-element 
    $doc->documentElement->appendChild($chapter); 
    //save it into the file 
    $doc->save('book.xml'); 
?> 
+0

うん、私はそのリンクを訪問し、例が私を少し混乱。基本的に.. xmlファイルを開き、親ノード内に新しい要素を作成するパスを作成し、その新しい要素の2つのノードをそれぞれの値を持つテキストノードと共に作成し、その新しい要素全体をルート? (新しいノードを親ノードに追加する)? – Vaughn

+0

私は私の答えに実際の例を入れました。フラグメントを使用する方が簡単です(これは公式のDOM標準ではなく、少し心が汚いです):http://de.php.net/manual/en/domdocumentfragment.appendxml.php –

+0

完全に動作しますMolle博士に感謝します。私が必要としていたのは、これのためのより明確な例だったので、私はこれのための基本的な構造を知ることができた。 – Vaughn

関連する問題