php - How to Convert string in xml and loop the Node?
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'};
}
Answer
Solution:
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"
Answer
Solution:
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);
Source