Question

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");
Was it helpful?

Solution

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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top