0

I have a problem with SimpleXMLElement.
I have to create a XML as here:

<p:father>
  <child></child>
</p:father>

If I try to do this with SimpleXMLElement result is:

<p:father>
  <p:child></p:child>
</p:father>

So all children have the same namespace. PHP code is:

$xml = new SimpleXMLElement('<p:father xmlns:p="http://example.com" />');
$xml->addChild('child');

Can anyone help me? I have to do this in order to create xml for Eletronical Invoicing.

3
  • “So all children have the same namespace.” - can’t reproduce, your code results in <child/> across all PHP versions, see 3v4l.org/lpt4g (But the warnings shown there already suggest that you are not currently handling creation of a namespaced element correctly to begin with.) Commented Dec 5, 2018 at 15:33
  • I have to do an XML that has this format. 3v4l.org/HEdB3 Commented Dec 5, 2018 at 15:38
  • Hi, I've edited your question to include a minimal reproducible example - a piece of code that someone can actually run to reproduce your problem. Please try to do this in future questions, as your previous example was not valid XML, leaving people to guess what you were actually doing. Commented Dec 10, 2018 at 13:31

1 Answer 1

1

The problem here seems to be that you are mixing namespaced elements with non-namespaced elements: you give a namespace the prefix p:, but don't set any default namespace for non-prefixed elements. SimpleXML seems to be "helpfully" setting your child element to be in the p: namespace rather than in no namespace at all.

The cleanest solution I can find is to define a namespace URI for your unprefixed elements, and then passing that to the addChild call:

$xml = new SimpleXMLElement('<p:father xmlns:p="http://example.com/prefixed" xmlns="http://example.com/default" />');
$xml->addChild('child', null, 'http://example.com/default');
echo $xml->asXML();

Which results in:

<?xml version="1.0"?> <p:father xmlns:p="http://example.com/prefixed" xmlns="http://example.com/default"><child/></p:father>
Sign up to request clarification or add additional context in comments.

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.