0

I am new in programming and want help. I want to save 2 variable's value in 4 tags and that group of tags will print as many times as user want in .xml file. how can i do this ? Is there any loop or recursion function ?

my code is this:

$variable1='abc';
$variable2='xyz';

$xml->channel->item = ""; 
$xml->channel->item->addChild('title', $variable1);
$xml->channel->item->addChild('link', $variable2);
$xml->channel->item->addChild('description', $variable1);

out put is this :

<item>
      <title>4</title>
      <link>4</link>
      <description>4</description>
</item>

I want to print this item tag with its sub tags as many time as user want.

1 Answer 1

1

You need to create a SimpleXMLElement object, then add "item" as a child and set that result to a variable. Then you can add more children (title, link, description) to that child.

$data = [
    [
        'title' => 'Made up Title',
        'link' => 'http://madeupwebsite.com',
        'description' => 'Hello world'
    ],
    [
        'title' => 'Made up Title 2',
        'link' => 'http://madeupwebsite2.com',
        'description' => 'Hello world2'
    ]
];

$xml = new SimpleXMLElement('<xml/>');

foreach ($data as $item) {

    $child = $xml->addChild('item');

    foreach ($item as $key => $value) {
        $child->addChild($key, $value);
    }

}

print($xml->asXML());
Sign up to request clarification or add additional context in comments.

4 Comments

i got this error: Fatal error: Call to a member function addChild() on a non-object in C:\xampp\htdocs\restaurant\test.php on line 177
on line number 177 i have this statement: $xml->channel->item->addChild('title', $tty);
Because you must add item as a child node of channel instead of setting it to an empty string as you've done ($xml->channel->item = ""). Call $xml->channel->addChild('item') and then you will be able to call addChild on $xml->channel->item
Happy to hear it! Would you mind marking the answer as correct? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.