0

I have a simple xml string. I am trying to convert it into xml and need to save 2 records in DB for it. First node will go seperate record and 2nd node will go as a seperate record. But it's not working. This is string.

$getXml = '<Nodes>
<NODE>
<RANGE-START>200</RANGE-START>
<RANGE-END>244</RANGE-END>
<QTY>45</QTY>
</NODE>
<NODE>
<RANGE-START>50</RANGE-START>
<RANGE-END>52</RANGE-END>
<QTY>2</QTY>
</NODE>
</NODES>
';

This is code

$xml=simplexml_load_string($getXml);
foreach( $xml->node as $item ) 
{
    echo $arrXml = $item->{'RANGE-START'};
}
parv
  • 95
  • 8
  • Your XML is invalid, there should be only 1 root node (you have 2 `` elements). Add a node round all of the XML and it should work. – Nigel Ren Jan 13 '21 at 09:23
  • where's the parent node? it's invalid that's why it doesn't work. just wrap it around with a `markup here` or something to make it valid – Kevin Jan 13 '21 at 09:24
  • While developing, make sure you [show all errors and warnings](https://stackoverflow.com/questions/5438060/showing-all-errors-and-warnings). This should throw a bunch of warnings. – M. Eriksson Jan 13 '21 at 09:24

2 Answers2

0

You are missing one main tag in the XML that will contain all the nodes.

Try this:

$getXml = '<nodes>
<node>
<RANGE-START>200</RANGE-START>
<RANGE-END>244</RANGE-END>
<QTY>45</QTY>
</node>
<node>
<RANGE-START>50</RANGE-START>
<RANGE-END>52</RANGE-END>
<QTY>2</QTY>
</node>
</nodes>';

$xml=simplexml_load_string($getXml);
foreach( $xml->node as $item )
{
    echo $arrXml[] = $item->{'RANGE-START'};
}
var_dump($arrXml);

If you want to save the whole node, then you need to save it to xml:

$xml=simplexml_load_string($getXml);
foreach( $xml->node as $item )
{
    echo $arrXml[] = $item->saveXML();
}
var_dump($arrXml);
Odei Alba
  • 116
  • 3
  • i have changed format of xml. But i need to save $getxml 2 times in DB like first record xml will be 200 244 45 and rnd record xml will be 50 52 2 – parv Jan 13 '21 at 10:46
  • @parv then just save the node to xml again `echo $arrXml[] = $item->saveXML();` – Odei Alba Jan 14 '21 at 12:36
0

XML is case sensitive. You will have to address the NODE elements as $xml->NODE.

$getXml = '<NODES>
<NODE>
<RANGE-START>200</RANGE-START>
<RANGE-END>244</RANGE-END>
<QTY>45</QTY>
</NODE>
<NODE>
<RANGE-START>50</RANGE-START>
<RANGE-END>52</RANGE-END>
<QTY>2</QTY>
</NODE>
</NODES>
';

$xml=simplexml_load_string($getXml);
foreach( $xml->NODE as $item ) 
{
    var_dump((string)$item->{'RANGE-START'});
}

Output:

string(3) "200"
string(2) "50"
ThW
  • 19,120
  • 3
  • 22
  • 44