1

I want to create an XML with the following structure:

<?xml version="1.0" encoding="UTF-8"?>
<content>
    <!-- content goes here -->
</content>

I originally created the xml node like this:

$xml = new SimpleXMLElement('<xml/>');
$content = $xml->addChild('content');
// add data to content

but that doesn't allow for adding attributes to the xml node, so now I do this:

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>'
                      .'<content></content>');

For some reason it doesn't work without adding the content node, but whatever, it gets the structure right.

Now, how do I assign the content node to a variable like I did above, so I can add data to it?

3 Answers 3

1

In your case the $xml variable is equal to the content node just try the following:

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>'
    .'<content></content>');
$xml->addAttribute('Attribute', 'value');
$xml->addChild('node_name', 'value');
echo $xml->asXML();

this should print

<?xml version="1.0" encoding="UTF-8"?>
<content Attribute="value"><node_name>value</node_name></content>
Sign up to request clarification or add additional context in comments.

Comments

1

E.g.

<?php
$content = new SimpleXMLElement('<content />');
$content['attr']='value';

echo $content->asXML();

prints

<?xml version="1.0"?>
<content attr="value"/>

--- edit:
To keep the encoding=utf-8:

$content = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>
<content />');

2 Comments

Yes, but how do I assign the content node to a variable to actually work with it when I do it like that?
xml version 1.0 default encoding is UTF-8, so there is no need to "keep" it :)
1

An XML document must have at least one element. That is the document element. In your question this is the content element.

You can create a SimpleXMLElement of it by just instantiating it with this minimum string:

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

The variable $xml then represents that element. You can then...

  • ... add attributes: $xml['attribute'] = 'value';
  • ... set the content-text: $xml[0] = 'text';
  • ... add child-elements: $xml->child = 'value';

This exemplary line-up then would have created the following XML (beautified, also: online demo):

<?xml version="1.0"?>
<content attribute="value">
  text
  <child>value</child>
</content>

Comments

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.