Tag Archives: xml

Cakephp 3- How to read a remote Xml file

23666One of the great things about CakePHP is that it has a lot of built in librarys.  Heres an example of how to read a remote XML file.

 

 

 

use Cake\Utility\Xml;
use Cake\Network\Http\Client;

//XML file you want to read in
$url="http://store.steampowered.com/feeds/newreleases.xml";

//read a remote xml file
$http = new Client();
$response = $http->get($url);
$xml = Xml::build($response->body());


//Method 1 using SimpleXMLElement Object
//loop the item elements array of xml file
foreach($xml->channel->item as $item){
	//need to cast to string
	debug ((string)$item->title);
	debug ((string)$item->link);
}


//Method 2 convert xml to array
$xml = Xml::toArray($xml);

//loop elements of array
foreach($xml['rss']['channel']['item'] as $item){
	debug ('Title:'.$item['title']);
	debug ('Link:'.$item['link']);
}

The result will print out the list of items from the feed;
http://store.steampowered.com/feeds/newreleases.xml

cakexml

 

 

 

 

 

 

More info here;
http://book.cakephp.org/3.0/en/core-libraries/xml.html#importing-data-to-xml-class

How to add REST features to your Cakephp 3 App

23666To add REST features to your CakePHP 3 you simply need to add two lines of code to your controller;

This will allow any action in the controller to be viewed as JSON or XML .

To view your action index as JSON simply;

http://localhost/mycakeapp/mycontroller/index.json

Rest Examples:
http://localhost/mycakeapp/mycontroller/view/1.json

http://localhost/mycakeapp/mycontroller/view/1.xml

 

public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}

 

Then in routes.php file /config/routes.php add;

Router::extensions(['json', 'xml']); //ensure this is before the below line.
Router::scope('/', function (RouteBuilder $routes) {

More info from the manual:
http://book.cakephp.org/3.0/en/development/routing.html#resource-routes

Cakephp Tip #3 – Requesting JSON or XML

The newest version of Cakephp makes it even easier to make a JSON or XML request.

Add the request handler component to your controller;

public $components = array('Paginator','RequestHandler' );

create your action in your controller;
eg

public function testjson() {
$this->set('posts', $this->paginate());
$this->set('_serialize', array('posts'));
}

To access either the JSON or XML version simply append .json or .xml to the action name;

http://localhost/myapp/posts/testjson.json

http://localhost/myapp/posts/testjson.xml

Manual: