Wednesday, March 7, 2012

Retrieve the XML node value using PHP

When we want to read the XML tag value, we may use simple_xml_load or DOMdocument to read it and will get the particular node value. Below is the simple PHP function to retrieve the XML node value by passing the XML as string and passing the starting XML tag and ending XML tag.


function get_value_by_tag_Name( $str, $s_tag, $e_tag)
{
$s = strpos( $str,$s_tag) + strlen( $s_tag);
$e = strlen( $str);
$str= substr($str, $s, $e);
$e = strpos( $str,$e_tag);
$str= substr($str,0, $e);
$str= substr($str,0, $e);
return  $str;
}

Here $str is the XML which we are passing as a string, $s_tag is the Starting tag(Ex: '<EmployeeDetails'>) and $e_tag is the ending tag (Ex: '</EmployeeDetails>'). By passing the values it returns the node value.

So, it reduces the parsing XML and DOM Document steps.