Friday, June 3, 2016

PHP: XML File Reading using Simple XML

The simplest solution is to load the file and process the xml nodes as follows:

$xml = simplexml_load_file('myfile.xml');

$node1 = $xml->child1;

$node2 = $xml->child2;


However, in some instances the resulting xml is either blank or empty. In this case, we need to call the following method:

$xml = simplexml_load_file('myfile.xml');

echo $xml->asXML();


If none of the above steps work, we need to create a Simple XML Element as follows:


$content = file_get_contents($fileName);

$xml = new SimpleXMLElement($content);
$node1 = $xml->child1;

If you still have issues after all this, typecast the node values:

$node1 = (string)$xml->child1;


Sample XML: myfile.xml
<root>

   <child1>Child 1</child1>

   <child2>Child 2</child2>

</root>

No comments:

Post a Comment