0

I have a problem converting my string which has a structure of XML into a proper XML file.

My String looks like:

<product>
  <ID>12345</ID>
  <NAME></NAME>
</product>
<product>
  <ID>123</ID>
  <NAME></NAME>
</product>

And so on. The problem is that I get empty result if I use DOM.

$dom = new DomDocument('1.0', 'UTF-8');
$dom->loadXML($products);
$xml = $dom->saveXML($dom);

Output is:

string(39) "<?xml version="1.0" encoding="UTF-8"?>
"

How can I make this work? Or I just can add the html and root tags to this string and just parse it to the file?

1
  • 1
    You don't have a root node in your XML. Commented May 19, 2017 at 10:22

1 Answer 1

1

Your XML is not properly formatted. XML requires a root element.

If you change your XML to something like this:

<products>
    <product>
      <ID>12345</ID>
      <NAME></NAME>
    </product>
    <product>
      <ID>123</ID>
      <NAME></NAME>
    </product>
</products>

It should work as expected.

Adjusted code:

<?php
$dom = new DomDocument('1.0', 'UTF-8');
$dom->loadXML('<products>
    <product>
      <ID>12345</ID>
      <NAME></NAME>
    </product>
    <product>
      <ID>123</ID>
      <NAME></NAME>
    </product>
</products>');
echo $dom->saveXML();

Outputs:

<?xml version="1.0"?>
<products>
    <product>
      <ID>12345</ID>
      <NAME/>
    </product>
    <product>
      <ID>123</ID>
      <NAME/>
    </product>
</products>
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.