阅读&;使用PHP&;DOM


Reading & Appending Data to XML File using PHP & DOM

我目前正在使用php 5.5.15

这是我使用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>

这样的东西就足够了

$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>';
}