0

Here I generate on xml dynamically but in this i got the xml but in the last extra two tags came.

Here My xml

<Main>
<Mainrow>
<code>xxxx</code>
<itemname>AAAAA</itemname>
<qty>5.000</qty>
</Mainrow>
</Main>/Mainrow></Main>

My loop

$stock_txt = '<Main>';
            foreach($results as $key => $datas){
                   $stock_txt .= '<Mainrow>';
                    foreach($datas as $val=>$res){
                        $stock_txt .= '<'.$val.'>'.$res.'</'.$val.'>';
                    }
                        $stock_txt .= '</Mainrow>';
                }
           $stock_txt .= '</Main>';
           $dom->loadXML($stock_txt);
           $dom->save($myFile); // myFile -- my path to save file
           fwrite($fh, $stock_txt);     

how to trim the last

/Mainrow and Main

I tried

substr($stock_txt,-22); but failed to get the XML generation

Thanks in advance

7
  • 1
    </Main>/Mainrow> that is buggy syntax, check that first Commented Nov 16, 2016 at 13:58
  • 2
    Please use XMLWriter for making XML Data. Commented Nov 16, 2016 at 14:00
  • hi, I when i generate the xml using that loop I got like that </Main>/Mainrow> at last. how to remove or is any mistake in my loop Commented Nov 16, 2016 at 14:00
  • The loop looks fine. Cant see any errors there. Try to change this: '>'.$res.'< to '><![CDATA['.$res.']]>< and look what happens. Commented Nov 16, 2016 at 14:03
  • 1
    What does fwrite($fh, $stock_txt); if you already using $dom->save($myFile);. And normaly this line $stock_txt .= '</Main>'; adds only one </Main> into the xml. Is this maybe old data or other runnning code? Commented Nov 16, 2016 at 14:09

1 Answer 1

1

Do not create XML as text, use DOM or XMLWriter methods to create/add the nodes. You load your XML string into DOM and save it. So why not use DOM methods from the start:

$results = [
  [
    'code' => 'xxxx',
    'itemname'=> 'AAAAA',
    'qty'=> '5.000'
  ]
];

$document = new DOMDocument();
$main = $document->appendChild($document->createElement('Main'));
foreach ($results as $datas) {
  $row = $main->appendChild($document->createElement('Mainrow'));
  foreach ($datas as $name => $value) {
     $row
       ->appendChild($document->createElement($name))
       ->appendChild($document->createTextNode($value));
  }
}

$document->formatOutput = TRUE;
//$document->save($myFile);
echo $document->saveXml();

Output:

<?xml version="1.0"?>
<Main>
  <Mainrow>
    <code>xxxx</code>
    <itemname>AAAAA</itemname>
    <qty>5.000</qty>
  </Mainrow>
</Main>
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.