2014-09-06 17 views
-1

我目前使用PHP 5.5.15閱讀和數據附加到使用PHP和DOM

這個XML文件是我用來編寫使用DOM稱爲comment.xml一個簡單的XML文件中的代碼。現在如下圖所示的文件結構就是我所需要的。我將不勝感激的是代碼示例,它允許我讀取所有用戶和評論,並將它們發送給html。還有代碼示例以追加到下面的文件。

任何幫助非常感謝。

/*** a new dom object ***/ 
$dom = new domDocument; 

/*** make the output tidy ***/ 
$dom->formatOutput = true; 

/*** create the root element ***/ 
$root = $dom->appendChild($dom->createElement("comments")); 

/*** create the simple xml element ***/ 
$sxe = simplexml_import_dom($dom); 

/*** add a user element ***/ 
$sxe->addChild("user", $User_Name); 

/*** add a comment element ***/ 
$sxe->addChild("comment", $Comment); 

$dom->save('comment.xml'); 

輸出上面的代碼是:

<?xml version="1.0"?> 
<comments> 
<user>Joe Blogs</user> 
<comment>This is a comment</comment> 
</comments> 
+0

我們有類似這種事情已經在現有的Q&A的示例代碼。通常不會要求提供代碼示例,但您可以通過搜索現有內容的示例性問題來利用它。詢問需要一個具體的編程問題,使問題完全清楚你在問什麼。這與一個精煉的,自我包含的例子最適合,這個例子說明了一個具體的編程問題。 – hakre 2014-09-08 11:52:04

回答

0

像這樣的東西就足夠了

$xmlStr = '<container><comments><user>Joe Blogs</user><comment>This is a comment</comment></comments><comments><user>John Doe</user><comment>This is another comment</comment></comments></container>'; 

$dom = new DOMDocument; 
$dom->loadXML($xmlStr); 
if (!$dom) { 
    echo 'Error while parsing the document'; 
    exit; 
} 

$xmlObj = simplexml_import_dom($dom); 


foreach($xmlObj->comments as $child) { 
    echo 'user: '.$child->user.'<br>'; 
    echo 'comment: '.$child->comment.'<br>'; 
    echo '-----------------<br>'; 
}