Asked 8 years ago
24 Dec 2016
Views 614
noob

noob posted

how to read xml easily in php


sample configuration.xml

...
<database>
	<name>test</name>
	<username>root</username>
	<password>admin</password>
	<host>localhost</host>
</database>
...


i made read xml code

$filename="configuration.xml";
$fp=fopen($filename);
$xmldata=fread($fp,filesize($filename));
fclose($fp);
$database_detail=$xmldata.explode("<name>");
echo $database_name=str_replace("</name>","",$database_detail[1]);


so its look very backward class work , and i think there should be more good way .


Mahesh Radadiya

Mahesh Radadiya
answered Nov 30 '-1 00:00


DOMDocument and DOMXPath is useful to parse the XML


       $doc = new DOMDocument();
	if ( $doc->load($filename) === false )
		return false;
	$xpath = new DOMXPath($doc);
	$rules = $xpath->query('/database/name');
	foreach ($rules as $entry) {
           echo $entry;
         }
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

simplexml_load_file or simplexml_load_string

load the xml file and grab the node as per its hierarchy.

 $xml = simplexml_load_file('configuration.xml');
echo  $xml->name ;
echo  $xml->username ;
echo  $xml->password ;
 
Post Answer