Patrik
Patrik

Reputation: 1327

PHP create XML from strings

I have some string in PHP, and I need to make XML from them.

Working examle :

$xml = <<<EOT
<?xml version="1.0"?>
  <ALL>
    <BLOCK id="1" >
      <TEXT name="A1" />
      <TEXT name="A2" />
    </BLOCK>
    <BLOCK id="2" >
      <TEXT name="B1" />
      <TEXT name="B2" />
    </BLOCK>
  </ALL>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);

What I actualy have and it does not work. :

$string1 = '<TEXT name="A1" />';
$string2 = '<TEXT name="A2" />';
$string3 = '<TEXT name="B1" />';
$string4 = '<TEXT name="B2" />';

$xml = <<<EOT
<?xml version="1.0"?>
  <ALL>
    <BLOCK id="1" >
        $string
        $string
    </BLOCK>
    <BLOCK id="2" >
        $string3
        $string4
    </BLOCK>
  </ALL>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);

Upvotes: 0

Views: 1241

Answers (1)

felipsmartins
felipsmartins

Reputation: 13549

I think you've forgotten to refer $string1 and $string2 vars:

It work for me:

$string1 = '<TEXT name="A1" />';
$string2 = '<TEXT name="A2" />';
$string3 = '<TEXT name="B1" />';
$string4 = '<TEXT name="B2" />';

$xml = <<<EOT
<?xml version="1.0"?>
  <ALL>
    <BLOCK id="1" >
        $string1
        $string2
    </BLOCK>
    <BLOCK id="2" >
        $string3
        $string4
    </BLOCK>
  </ALL>
EOT;


$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);

echo $dom->saveXML();

Upvotes: 1

Related Questions