How to read data from XML file using php

I have an XML file with data in it, I want to read the XML file, get the values ​​and display the values, I try to display RECIPIENT_NUM and TEMPLATE, but now I can only display TEMPLATE, but I can’t show RECIPIENT_NUM.below my code can anyone help me display RECIPIENT_NUM, thanks

XML

<?xml version="1.0" encoding="UTF-8"?>
<DOCUMENT>
   <VERSION>2.0</VERSION>
   <INVOICE_NUM>33</INVOICE_NUM>
   <PIN>14567894</PIN>
   <MESSAGE_TYPE>INSTANT_SEND</MESSAGE_TYPE>
   <COUNTRY_CODE>xxxxxxx</COUNTRY_CODE>
   <TEMPLATE>Dear Mrs Braem, this is a message from xxxxxxx. Kindly call us regarding your cleaning appoitnment tomorrow at 9.30. Thanks and Regards</TEMPLATE>
   <DATABASEINFO>
      <DATABASE_NAME>xxxxxx</DATABASE_NAME>
      <CLINIC_ID>1</CLINIC_ID>
   </DATABASEINFO>
   <MESSAGES>
      <MESSAGE>
         <SEND_DATE>2013-12-15</SEND_DATE>
         <ENTITY_ID>0</ENTITY_ID>
         <RECIPIENT_NUM>xxxxxxx</RECIPIENT_NUM>
         <MESSAGE_PARAMS />
      </MESSAGE>
   </MESSAGES>
   <CSUM>ffd6c84a1a89a0f2ebc8b1dc8ea1f4fb</CSUM>
</DOCUMENT>

Php

<html>
<body>

<?php
$xml=simplexml_load_file("/data/data/www/Message.xml");
print_r($xml);

echo $xml->TEMPLATE . "<br>";
echo $xml->RECIPIENT_NUM."<br>";
?>  

</body>
</html>
+3
source share
3 answers

You should look at the XML structure, you need to do

echo $xml->MESSAGES->MESSAGE->RECIPIENT_NUM."<br>";
+4
source

The DOM is more complicated, but maybe everything, try visiting the DOM vs. SimpleXML

Try the following:

$xml = new DOMDocument();
$xml->load('/data/data/www/Message.xml');
$data = array (           
      'template'       => $xml->getElementsByTagName('TEMPLATE')->item(0)->nodeValue,
       'recipient_num' => $xml->getElementsByTagName('RECIPIENT_NUM')->item(0)->nodeValue          
        );         
 var_dump($data);
0
source

You can use the following codes, this works for me.

$xml = simplexml_load_file("/data/data/www/Message.xml");
foreach($xml->children() as $key => $children) {
  print((string)$children->TEMPLATE); echo "<br>";
  print((string)$children->RECIPIENT_NUM); echo "<br>";
  // Remaining codes here.
}
0
source

All Articles