SimpleXML

Load XML file:

$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "<br />";

foreach($xml->children() as $child){
echo $child->getName() . ": " . $child . "<br />";
}

 

Get attribute values:

$att = $node->attributes();
echo $att["label"];

 

Find the first node with a attribute value:
$node = $xml->xpath(‘//‘ . $table . ‘/item[@formName=”‘ . $formFieldName . ‘”][1]‘);
*Above statement will search any place in this XML and return an Array object:
(String)$challenge[0]->label[0];

Search from root node:
$node = $xml->xpath(‘/rootNode/child’);

http://www.w3schools.com/xpath/xpath_syntax.asp

Another practical example:

	function get_error($code){
		$xml = simplexml_load_file(ADMIN_DIR . "/xml/error.xml");
		$arr = $xml->xpath('//item[@id="' . $code . '"]/' . $this->lang_code);
		//echo var_dump((String)$arr[0]);
		//exit();
		return (String)$arr[0];
	}

 

Get attributes:

$node = $xml->xpath('/nodes/cat[@name="case_type"]/item[@id="3"]')[0];
//echo var_dump($node->attributes()->label);
echo $node->attributes()->label;
exit();

 

3 thoughts on “SimpleXML

Comments are closed.