dqndc26628 2014-09-06 13:09
浏览 43

使用PHP和DOM读取和附加数据到XML文件[重复]

This question already has an answer here:

I am currently using php 5.5.15

This is the code I use to write a simple xml file called comment.xml using DOM. Now the structure of the file as illustrated below is what I require. What I would appreciate is code sample which will allows me to read all users and comments and out put them say to html. and also code sample to append to the file below.

any help much appreciated.

/*** 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');

The output for the above code is:

<?xml version="1.0"?>
<comments>
<user>Joe Blogs</user>
<comment>This is a comment</comment>
</comments>
</div>
  • 写回答

1条回答 默认 最新

  • doqpm82240 2014-09-06 19:02
    关注

    Something like this would suffice

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度