Pages

How to Parse XML in CakePHP

Hi all, this is a basic tutorial on how to parse  xml file in cakephp.
We all know that cakephp vastly utilizes the array concept in php. Here, I am going to explain you how to parse XML in CakePHP and convert it into an array.
Step1:
Get the XML Feed; for example you might be having an xml feed from a search engine or any other type of feed which is in xml. get the contents of the URL to do so, I’m going to create a function in my controller and utilize the XML helper.
create the function, say: parse_xml

function  parse_xml() {
App::import('Xml');
$raw_xml = file_get_contents("type your xml url here");
$parsed_xml = & new XML($raw_xml);

$parsed_xml = Set::reverse($parsed_xml);  // reversing the xml to array. this can be also used to convert an array to xml also.

return $parsed_xml;
}
That’s all.. everything done
to get the array to a variable
$xml_array = $this->parse_xml();
now try printing the array
echo "
";
print_r($xml_array)
die;

More Here


Courtesy:http://cakeleak.wordpress.com/2010/05/28/how-to-parse-xml-in-cakephp/

5 comments: