Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Monday, 7 April 2014

Reading XML file - PHP

 

The easiest and simplest way to read XML file is using SimpleXML.

 

We'll consider a simple XML file test.xml with the following nodes and values.


<!-- Test.xml --> 
<root>
   <node1>Hello</node1>
   <node2>World</node2>
    <node3>This is simple Example of Parsing XML files </node3>
<root>  
 


 Loading a XML file

$xml=simplexml_load_file("filename");

Parsing a Node value 

$node=$xml->node_name;
  

 Example to demonstrate the usage of simpleXML


<?php
$xml=simplexml_load_file("test.xml");
echo $xml ->node3;
 echo '<br/>';
foreach($xml->children() as $child)   // children() get all the child nodes in the XML file.
{
      echo 'Node_name: '.$child ->getName().'   ';      // displays the node_name.
     echo 'Node_value: '.$child.'<br/>';   // displays the node value.
}
?>  




Output will be displayed as follows


This is a simple example of parsing XML files
Node_name: node1 Node_value: Hello
Node_name: node2 Node_value: World
Node_name: node3 Node_value: This is a simple example of parsing XML files 











Nodes having nested nodes can be parsed using the above method by using foreach loop. 

for more Details refer
  1. http://www.w3schools.com/php/php_xml_simplexml.asp 
  2. http://www.php.net/manual/en/simplexml.examples-basic.php  
  3. http://www.php.net/manual/en/ref.xml.php 

Sunday, 6 April 2014

Including multiple PHP files.

Use of Including files.

  • Including multiple PHP files helps Maintainability
  • Huge blocks of code can be split into small useful blocks which can be included wherever necessary.
  • Re-usability of code.

How To 

  1. Using Require.
    • Produces a fatal-error (E_COMPILE_ERROR) and stops the script if the Code fails to load the Script file.
  2. Using Include
    • Produces a warning (E_WARNING) and Resumes the script upon failure. 
Based on Requirements choose whether to use Require or Include. 
 

 Syntax :  

<?php include 'script_name.php '  ?>
<?php require 'script_name.php'  ?>

Example


<!-- test.php --> 

echo " Hello World <br/>" ;
echo "This Message is Displayed  by the Included file test.php <br/> " ;



<!-- Main.php -->
<?php 
    echo "This is Displayed from main.php <br/>";
    include "test.php";
?> 

 Output

This is Displayed from main.php
Hello World
This message is Displayed from Test.php


For more Information refer
  1. http://www.w3schools.com/php/php_includes.asp
  2. http://www.php.net/manual/en/function.include.php