Reputation: 151
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
Upvotes: 0
Views: 208
Reputation: 19482
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>
Upvotes: 1