dpvmjk0479 2014-04-17 08:02
浏览 36
已采纳

PHP写入SimpleXML并保存

Having the following code, I need to do something:

XML

<?xml version="1.0" encoding="UTF-8"?>
<ToDoList>
    <Item>
        <Name>Complete this xml</Name>
        <Category>Programming</Category>
    </Item>
    <Data>
    </Data>
</ToDoList>

PHP

<html>
    <head>
        <style>
        b {
            font-size:30px;
        }
        h1 {
            font-size:40px;
        }
        i {
            font-size:18px;
        }
        span {
            font-size:24px;
        }
        </style>
    </head>
    <body>
        <?php
            $ToDoList = simplexml_load_file("list/todo.xml");
            $Name = $ToDoList->getName();
            echo("<h1>".$Name."</h1>");
            foreach($ToDoList->children() as $item){
                echo("<b>" . $item->getName() . " : " . $item . "<br></b>");
                foreach($item->attributes() as $name => $value){
                    echo("<i>attr. : " . $name . " = " . $value . "<br></i>");
                }
                foreach($item->children() as $subitem){
                    echo("<span>" . $subitem->getName() . " : " . $subitem . "<br></span>");
                }
            }
        ?>
    </body>
</html>

What I need to do is:

To write into xml and then save.

I want to write <Test>1</Test> in <Data></Data>. After that I want to save it back to list/todo.php.

I've tried reading the questions to write and save the xml, but neither of the methods worked.

What code should I use (in php) to solve this problem?

EDIT---

I tried to use this code, but it didn't work:

$NewItem = $ToDoList->ToDoList->addChild('Item');
$NewItem->addChild("Name","Test");
$NewItem->addChild("Category","Test");
$ToDoList->asXML("test.xml");
  • 写回答

1条回答 默认 最新

  • dsgdg54ef4365 2014-04-17 08:28
    关注

    Use like this. replace element with your element and child.this is sample code.

    $xml = new DOMDocument();
    $xml_item = $xml->createElement("Item");
    $xml_name = $xml->createElement("Name");
    $xml_category = $xml->createElement("Category");
    $xml_album->appendChild( $xml_name );
    $xml_album->appendChild( $xml_category );
    $xml->appendChild( $xml_album );
    
    $xml->save("test.xml");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办