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

//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;








More info here;

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;


Rest Examples:



public function initialize()


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:

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;

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;