For smart Primates & ROBOTS (oh and ALIENS ).

Showing posts with label CakePHP. Show all posts
Showing posts with label CakePHP. Show all posts

Monday, June 01, 2015

Parse XML in PHP with Attributes

Problem:
How to Parse XML in PHP with Attributes
Listed below the XML data.
Suppose you have a url which produce below XML data on request and you want to parse it in PHP including it's attribute for ex:  spell id="168839" minCount="1" maxCount="1" etc.

See below XML for full information:
<?xml version="1.0" encoding="utf-8"?>
<wowhead><item id="114811">
  <name>Hexweave Leggings</name>
  <level>640</level>
  <quality id="4">Epic</quality>
  <class id="4">Armor</class>
  <subclass id="1">Cloth Armor</subclass>
  <icon displayId="132245">inv_cloth_draenorcrafted_d_01pants</icon>
  <inventorySlot id="7">Legs</inventorySlot>
  <htmlTooltip>
    <table>
      <tr>
        <td><!--nstart-->
          <b class="q4">Hexweave Leggings</b>
          <!--nend--><!--ndstart--><!--ndend-->
          <span style="color: #ffd100">
            <br />
            Item Level<!--ilvl-->640</span>
          <br />
          <!--bo-->Binds when equipped
          <br />
          Unique-Equipped: Warlords Crafted (3)
          <table width="100%">
            <tr>
              <td>Legs</td>
              <th>Cloth</th>
            </tr>
          </table>
          <span><!--amr-->83 Armor</span>
          <br />
          <!--re-->
          <span class="q2">&lt;Random enchantment&gt;</span>
          <br />
          <span><!--stat5-->+184 Intellect</span>
          <br />
          <span><!--stat7-->+275 Stamina</span>
          <!--ebstats--><!--egstats--><!--e--><!--ps-->
          <br />
          Durability 120 / 120</td>
      </tr>
    </table>
    <table>
      <tr>
        <td>Requires Level<!--rlvl-->91
          <div class="whtt-sellprice">Sell Price:
            <span class="moneygold">41</span>
            <span class="moneysilver">61</span>
            <span class="moneycopper">90</span>
          </div>
        </td>
      </tr>
    </table>
  </htmlTooltip>
  <json>"appearances":{"6":[132245,""],"7":[132269,""],"8":[132254,""]},"armor":83,"bonustrees":[184],"classs":4,"displayid":132245,"flags2":8192,"id":114811,"level":640,"name":"4Hexweave Leggings","reqlevel":91,"slot":7,"slotbak":7,"source":[1],"sourcemore":[{"c":11,"icon":"inv_cloth_draenorcrafted_d_01pants","n":"Hexweave Leggings","s":197,"t":6,"ti":168839}],"specs":[64,256,63,62,257,265,258,266,267],"subclass":1</json>
  <jsonEquip>"appearances":{"6":[132245,""],"7":[132269,""],"8":[132254,""]},"armor":83,"avgbuyout":53990000,"displayid":132245,"dura":120,"int":184,"reqlevel":91,"sellprice":416190,"slotbak":7,"sta":275</jsonEquip>
  <createdBy>
    <spell id="168839" name="Hexweave Leggings" icon="inv_cloth_draenorcrafted_d_01pants" minCount="1" maxCount="1">
      <reagent id="111556" name="Hexweave Cloth" quality="2" icon="inv_tailoring_hexweavethread" count="100"/>
      <reagent id="110609" name="Raw Beast Hide" quality="1" icon="inv_misc_nativebeastskin" count="4"/>
    </spell>
  </createdBy>
  <link>http://www.wowhead.com/item=114811</link>
  </item></wowhead>


Solution:

Using simplexml_load_file we can parse XMl data.

Example:

<?php
$url='http://www.wowhead.com/item=114811&xml';
$xml = simplexml_load_file($url) or die("feed not loading");
foreach($xml->item  as $items){
    echo $items->name . "<br>";
echo $items->level . "<br>";
echo $items->quality . "<br>";
echo $items->quality['id'] . "<br>";
echo $items->class . "<br>";
echo $items->class['id'] . "<br>";
echo $items->subclass . "<br>";
echo $items->subclass['id'] . "<br>";
echo $items->icon . "<br>";
echo $items->icon['displayId'] . "<br>";
echo $items->inventorySlot . "<br>";
echo $items->inventorySlot['id'] . "<br>";
echo $items->htmlTooltip . "<br>";
echo $items->json . "<br>";
echo $items->jsonEquip . "<br>";
echo $items->createdBy->spell  . " : ";
echo $items->createdBy->spell['id']  ." : ";
echo $items->createdBy->spell['name']  ." : ";
echo $items->createdBy->spell['icon']  . " : ";
echo $items->createdBy->spell['minCount']  ." : ";
echo $items->createdBy->spell['maxCount']  . "<br>";
$created_by_count=0;
foreach($items->createdBy->spell  as $myspel){
if($myspel->count()>=1) {
    foreach($myspel as $child) {
                  $created_by_count++;
      echo $child->getName(). ' : '. $child['id']. ' : ' .$child['name'] . ' : ' . $child['quality']. ' : ' . $child['icon']. ' : ' . $child['count'] . '<br/>';
}
  }
  echo 'Count createdBy='.$created_by_count. "<br>";
echo $items->link . "<br>";
}
}
?>
Share:

Friday, April 10, 2015

Run custom sql query in CakePHP 3.0

Problem:

How to Run custom sql query in CakePHP 3.0

Solution & Example:

File : src\Model\Table\ArticlesTable.php
<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Datasource\ConnectionManager;
class ArticlesTable extends Table
{
    var $conn;
    public function initialize(array $config) {
        $this->conn = ConnectionManager::get('default');
    }
    function get_all_users($id) {
        $stmt = $this->conn->prepare('SELECT * from users WHERE id>= :id');
        $stmt->bind( ['id' => $id], ['id' => 'integer']);
        $stmt->execute();
        return $stmt->fetchAll('assoc');
     } 
}
?>

File: src\Controller\ArticlesController.php
<?php
namespace App\Controller;

use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
//use MyClass\MyClass;
use MyLib\UtilClass;

 class ArticlesController extends AppController
 {
     public $helpers = array('Html', 'Form');
     public function index() {

    }
    public function showarticles(){
         $data = $this->Articles->get_all_users(3);
         $this->set('data',$data);
    }
}


File: src\Template\Articles\showarticles.ctp
<?php
foreach ($data as $row){
               echo '<br/>'.$row['username']. '-------' . $row['password'];
         }
?>









Share:

Wednesday, April 08, 2015

How to create own custom class in cakephp 3.0

Problem:

How to use own custom class or library class in CakePHP 3.0
If you have own useful library and you want to use it in your CakePHP 3.0 MVC Framework then follow below steps.


Solution:

If you have good knowledge of Core PHP then It will be easy to create own custom class in CakePHP 3.0 and use it. follow below steps:

1# Create the folder "MyLib" at root of CakePHP 3.0 structure where bin,config,logs folders are showing. you can also create it in the "vendor" folder but I think we should not create in there.

2# Create "UtilClass.php" file in the "MyLib" folder.

3# And last use it in your controller with it's path.

Example:

1# Create the folder "MyLib" at root of cakephp 3.0 structure where bin,config,logs folders are showing.

2# Create "UtilClass.php" file in the "MyLib" folder with below code:
<?php
namespace MyLib; //it is important,it is folder name
class UtilClass
{
    public function show()
    {
        return 'I am from my custom class in cakephp 3.0';
    }
}
?>


3# Use is as below code in any controller:
<?php
use MyLib\UtilClass;
 class TransportersController extends AppController
 {
     public function index() {

    }

    public function showtransporter(){
      require_once(ROOT .DS. "MyLib" . DS . "UtilClass.php");
      $util_obj = new UtilClass();
      echo $util_obj->show();

  }
}
?>
Share:

Tuesday, April 07, 2015

Model in CakePHP 3.0

Problem:

CalePHP 3.0 is different than it previous versions. Lot of things removed. In new CakePHP 3.0  
How to use Model in CakePHP 3.0 using new ORM model

Solution:

See below example

Example:


Create ArticlesController.php controller in "src\Controller" folder
<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
class ArticlesController extends AppController
{
     public function index() {

     }
    public function showarticles() {
        $data = $this->Articles->find();
        foreach ($data as $row){
          echo $row->title;
       }
    }
}

ArticlesTable.php in "src\Model\Table" folder
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class ArticlesTable extends Table
{

}
?>

Create Article.php in "src\Model\Entity" folder
<?php
// src/Model/Entity/Article.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Article extends Entity
{
       
}
?>






Share:

Saturday, April 04, 2015

custom query in cakePHP 3.0

Problem:

How to execute custom query in cakePHP

Solution:

Use ConnectionManager::get() and it's method newQuery() you can pass custom sql query

Example:


Change your database information in "config\app.php" file as below:

  'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'username' => 'root',
            'password' => '',
            'database' => 'petro_app',
            'encoding' => 'utf8',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
            'quoteIdentifiers' => false,
        ],
        ],
    ],


At the top in php code file where you want to execute sql query access ConnectionManager class as below:

use Cake\Datasource\ConnectionManager;

In method run sql query as below:
File name HardSelectionController.php   with complete code


use Cake\Datasource\ConnectionManager;

class HardSelectionController extends AppController  {

    public function showhardselection() {
      $conn = ConnectionManager::get('default');
      $query = $conn->newQuery();
     $query->select('*')
                ->from('user_info');
                ->where(['active' => true]);
    foreach ($query as $row) {
         echo $row['u_login'];
    }
}
}
Share:

Form in CakePHP 3.0

Problem:

How to create Form in CakePHP 3.0

Solution:

To create form in CakePHP 3.0 you need to use $this->Form->create() and along with this also use
echo $this->Form->input(), $this->Form->label(), $this->Form->text(), $this->Form->button() and never forget that every for must close with $this->Form->end(array('')) method.


Example:

Create this view file  "showhardselection.ctp" under "src\Template\HardSelection" folder.
<?php
echo $this->Form->create('UserForm', array('url' => array(
                        'controller' => 'HardSelection',
                        'action' => 'showsubmitdata')));
echo $this->Form->input('email');
echo $this->Form->label('username', 'Your username');
echo $this->Form->text('username');
echo $this->Form->button('Submit');
echo $this->Form->end(array(''));
?>

Create this controller file "HardSelectionController.php" in"src\Controller" folder.
<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;

class HardSelectionController extends AppController
 {
     public function index() {

    }
    public function showhardselection(){
       
    }
    public function showsubmitdata() {
        if($this->request->is('post')) {
            $email = $this->request->data['email'];
            $username = $this->request->data['username'];
            $this->set('email',$email);
            $this->set('username',$username);           
        }
    }
}

Create this view file  "showsubmitdata.ctp" under "src\Template\HardSelection" folder.
<?php
if(isset($email)) {
    echo 'user email:'.$email;   
}
if(isset($username)){
    echo '<br/>user name:'.$username;   
}
?>

Share:

Friday, April 03, 2015

How to change default controller in CakePHP 3.0

Problem:

How to change default controller in CakePHP 3.0. You know that default page of CakePHP 3.0 is Pages and it's action is display.

Solution:

To change default controller in CakePHP 3.0 open config.php which is located under "config" folder.
and change :

$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
TO
$routes->connect('/', ['controller' => 'Welcome', 'action' => 'index', 'home']);

Where Welcome is your created controller.

Share:

Thursday, April 02, 2015

Notice (8): Undefined variable in cakephp

Problem:

You can get the error message Notice (8): Undefined variable in CakePHP while passing variable value from Controller to View. How to overcome this error?




Solution:

If you mistakenly create a method in predefined Controller "PagesController.php" which is automatically created by default. So don't touch or use "PagesController.php". you need to create own Controller ans create method and pass variable.
In other clear wording "do not use PagesController.php file, create own controller class"

Example:

See below incorrect code:
File:    src\Controller\PagesController.php

<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;

class PagesController extends AppController
{
    public function display()
    {
        $path = func_get_args();

        $count = count($path);
        if (!$count) {
            return $this->redirect('/');
        }
        $page = $subpage = null;

        if (!empty($path[0])) {
            $page = $path[0];
        }
        if (!empty($path[1])) {
            $subpage = $path[1];
        }
        $this->set(compact('page', 'subpage'));

        try {
            $this->render(implode('/', $path));
        } catch (MissingTemplateException $e) {
            if (Configure::read('debug')) {
                throw $e;
            }
            throw new NotFoundException();
        }
    }
   
    public function myshow() {
      $this->set('color', 'pink');
    }
}

File: \src\Template\Pages\myshow.ctp
<?php
   echo $color;
?>


See below Correct code:
Create a new File BooksController
File:  src\Controller\BooksController.php

<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
class BooksController extends AppController
{    
      public function index()
    {

    }
    public function myshow() {
       $this->set('color','pink');
    }
}

Create a new file myshow.ctp
File: \src\Template\Books\myshow.ctp
<?php
   echo $color;
?>

So do not use PagesController.php file, create own controller class





Share:

Ads Inside Post

Powered by Blogger.

Archive