After spending one whole evening, I found out CakePHP has its own XML class for handling xml files. In the meantime, i tried SimplePie (for RSS only, not XML), SimpleXML, and XMLize. But still they werent of any great help compared to cakephp's core XML class.
How to parse it then?
First of all, you need to import the XML class in your controller class using App::import(). Here is the controller class parsing a particular xml file and printing out (like print_r) the returned array.
Controller class:
<?
class ParseController extends AppController {
var $name = "Parse";
var $uses = array('MyModel');
function xml() {
// import XML class
App::import('Xml');
// your XML file's location
$file = "my_xml_file_location.xml";
// now parse it
$parsed_xml =& new XML($file);
$parsed_xml = Set::reverse($parsed_xml);
// see the returned array
debug($parsed_xml);
}
}
?>
class ParseController extends AppController {
var $name = "Parse";
var $uses = array('MyModel');
function xml() {
// import XML class
App::import('Xml');
// your XML file's location
$file = "my_xml_file_location.xml";
// now parse it
$parsed_xml =& new XML($file);
$parsed_xml = Set::reverse($parsed_xml);
// see the returned array
debug($parsed_xml);
}
}
?>
6 comments:
One question
how to go the other way with cake?
You have any array - and want to save it as xml structered file
thx :)
euro - check out http://book.cakephp.org/view/380/xml a helper that will take an array and create xml.
class XmlTestController extends AppController
{
var $name = "XmlTest";
var $uses = 'Admin';
function index()
{
App::import('Xml');
// your XML file's location
$file = "my_xml_file_location.xml";
// now parse it
$parsed_xml =& new XML($file);
$parsed_xml = Set::reverse($parsed_xml);
}
}
I am using this code to fetch xml value but it showing me Class 'App' not found in path/app/controllers/xml_test_controller.php on line 25
how to solve it, guide me please
i think you are using cakephp1.1. you need to have the latest version 1.2 for 'App' class.
what if i want to parse a file on someother location , for example some sitemap of some website?? like www.mysite.com/sitemap.xml
I found this on: http://www.lenniez.nl/blog/category/CakePHP
about using remote xml files, rather than local files, for parsing:
3. The XML library
Coming to the next point, the XML library. I did not know CakePHP had an XML core library and that's why I had to use 'simplexml_load_string'. With the XML library you can easily convert a string to an XML object.
$xml = new Xml($input);
$xml = Set::reverse($xml);
You can even get a remote XML file by using an URL!
$xml = new Xml('http://ws.audioscrobbler.com/1.0/user/LennieZ/recenttracks.xml');
$xml = Set::reverse($xml);
Post a Comment