2011-08-26 52 views
0
function xmlParse() { 

    $fh = fopen('schools/' . $this->id . '/books/school_books.xml', 'a'); 


    $xmlstr = "<?xml version='1.0' ?>\n" . 
      "<rows></rows>"; 

    // create the SimpleXMLElement object with an empty <book> element 
    $xml = new SimpleXMLElement($xmlstr); 


    $x = 0; 

    // add some more child nodes 
    for ($i = 0; $i < sizeof($this->students); $i++) { 

     $this->students[$i]->getmyBooks(); 


     for ($j = 0; $j < sizeof($this->students[$i]->myBooks); $j++) { 



      $row = $xml->addChild("row"); 
      $row->addAttribute("id", $x); 
      $row->addChild("cell", $this->students[$i]->myBooks[$j]->owner); 
      $row->addChild("cell", $this->students[$i]->myBooks[$j]->title); 
      $row->addChild("cell", $this->students[$i]->myBooks[$j]->category); 
      $row->addChild("cell", $this->students[$i]->myBooks[$j]->price); 
      $row->addChild("cell", $this->students[$i]->myBooks[$j]->description); 
      $row->addChild("cell", "Test"); 
      $x++; 

      fwrite($fh, $xml->asXML()); 

     } 



    } 


} 

我知道問題是什麼:它的fwrite($ fh,$ xml-> asXML());循環與XML的fwrite

如果我一直在循環內調用它並不追加它,它會從頭開始繼續使用xml文檔並再次發佈標籤。

我的問題是,它不斷從xml標籤再次寫入...而不是繼續xml。如果我只爲1名學生做這件事,那麼它就是完美的,但是當我嘗試循環所有學生時,它會一直打印xml標籤,而不是繼續學習下一個學生。

<?xml version="1.0"?> 
    <rows> 
    <row id="0"> 
     <cell>Owner</cell> 
     <cell>test</cell> 
     <cell>Math</cell> 
     <cell>11</cell>   
     <cell>test</cell> 
     <cell>Test</cell> 
    </row> 
    </rows> 

    <?xml version="1.0"?> 

繼續下一個然後它一次又一次地做xml標記。

這是怎麼它看起來像一個學生:

<rows> 
    <row id="0"> 
     <cell>Owner</cell> 
     <cell>Calculus III</cell> 
     <cell>Math</cell> 
     <cell>82</cell> 
     <cell>This book is in great condition! Available asap.</cell> 
     <cell>Test</cell> 
    </row> 
    <row id="1"> 
     <cell>Owner</cell> 
     <cell>Discrete Mathematics</cell> 
     <cell>Math</cell> 
     <cell>62</cell> 
     <cell>This book is in poor condition.</cell> 
     <cell>Test</cell> 
    </row> 
    <row id="2"> 
     <cell>Owner</cell> 
     <cell>Calculus I</cell> 
     <cell>Math</cell> 
     <cell>12</cell> 
     <cell>Really good book.</cell> 
     <cell>Test</cell> 
    </row> 
    </rows> 

回答

1

你真的找file_put_contents($name, $contents)。該函數全部添加所有內容,所以您可以在循環結束時調用一次。

的代碼可能看起來像:在另一方面

// after i >= sizeof($this->students) 
file_put_contents('schools/' . $this->id . '/books/school_books.xml', 
        $xml->asXML()); 

FWRITE,附加了一個文件,每一次它被調用。這意味着它會將XML的內容添加到文件sizeof($this->students)次,這就是您現在看到的內容。

順便說一句,取決於sizeof($this->students)的大小,你可能想聲明一個局部變量來緩存,在你看之前,sizeof它會被每次調用。

$studentSize = sizeof($this->students); 
for ($i = 0; $i < $studentSize; $i++) { 

在另一方面,你可能要改變,要foreach循環(不能描述如何的時刻,但如果我還記得,我會在以後添加在)。

+0

太棒了,謝謝哈哈我知道有一個簡單的方法。我已經寫了一個函數來將每個單獨寫入一個文件,然後追加這個對象,這會很痛苦。謝謝,非常感謝。像魅力一樣工作。 – mnouh1