The following codes are from http://d.hatena.ne.jp/dix3/20081002/1222899116 and codes are working well.
This is an example of using snoopy in codeigniter.
Q1. Am I correct to say that I can't use,
$this -> load -> library('snoopy')
since Snoopy.php does not create an object. And the example below is the way to do it?
If so, can you explain/direct me an tutorial or explanation of how to do it in details?
if ( ! class_exists('Snoopy'))
{
require_once(APPPATH.'libraries/Snoopy'.EXT);
}
Q2. Why do the author use
$to_specialchars=true
Is it needed for this?
Q3. Could you explain APPPATH and EXT.
APPPATH.'libraries/Snoopy'.EXT
I checked it in php.net but I could not find it. EXT must be extension, but can I use anywhere?
Thanks in advance.
I have a snoopy in application/library/Snoopy.php
I have application/library/Snoopy.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Scraping{
var $c;
function Scraping(){
if ( ! class_exists('Snoopy'))
{
require_once(APPPATH.'libraries/Snoopy'.EXT);
}
$this -> c = new Snoopy();
}
function getWebHtml($url="",$to_specialchars=true){
$this ->c -> fetch( $url );
$str = mb_convert_encoding( (string) $this -> c -> results,"UTF-8","auto");
return ($to_specialchars) ? htmlspecialchars($str , ENT_QUOTES , "UTF-8" ) : $str ;
}
function getWebText($url="",$to_specialchars=true){
$this -> c -> fetchtext( $url );
$str = mb_convert_encoding( (string) $this -> c -> results,"UTF-8","auto");
return ($to_specialchars) ? htmlspecialchars($str , ENT_QUOTES , "UTF-8" ) : $str ;
}
function getWebLinks($url=""){
$this -> c -> fetchlinks( $url );
return (array) $this-> c -> results ;
}
function getWebLinksText($url="",$delimiter="<br>"){
$arr = $this-> getWebLinks($url) ;
$ret ="";
foreach($arr as $k => $v){
$ret .= $v . $delimiter ;
}
return $ret;
}
} //endofclass
/* End of file Scraping.php */
/* Location: ./application/libraries/Scraping.php */
?>
I have a controller application/controller/mytasklist.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mytasklist extends Controller {
function Mytasklist()
{
parent :: Controller();
$this -> load -> helper( 'url' );
}
function index()
{
$data = "";
$this -> _SetTpl( $data );
}
function _SetTpl( $data )
{
$this -> load -> library("scraping");
$data["scraping"]["text"] = $this-> scraping -> getWebText("http://www.example.com/");
$data["scraping"]["html"] = $this-> scraping -> getWebHtml("http://www.example.com/");
$data["scraping"]["link"] = $this-> scraping -> getWebLinksText("http://www.example.com/","\n");
$tpl["page_title"] = "Welcome";
$tpl["main_content"] = $this -> load -> view( 'tasklist_view', $data , true );
$this -> load -> view( 'base_view', $tpl );
}
}
And I have a view, application/view/base_view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="keywords" content="keyword here" />
<meta name="description" content="description here" />
<title><?php if(isset($page_title)){echo $page_title ;}?></title>
<?php if(isset($xajax_js)){echo $xajax_js ;}?>
<link href="http://127.0.0.1/ci_day4/css/mystyle.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="container">
<div id="rightblock">
<div id="content">
<?=$main_content?>
</div>
</div>
</div>
</body>
</html>
Q1. You can use:
$this->load->library('snoopy');
In your controllers. And create a new instance like so:
$snooper = new Snoopy();
The reason they are using:
if (!class_exists('Snoopy')) {
require_once(APPPATH.'libraries/Snoopy'.EXT);
}
Is because you will get a fatal error if you try and use $this->load->library(), since the loader class is not available in the library. You can call it in a controller is because your controllers extend the controller class, which extends the ci_base class, which extends the ci_loader class which is where the functionality to make calls like $this->load comes from. The Scraping class that you've shown here does not. If you dig down you'll see that the loader is basically using include_once to include whatever class, helper etc. you're trying to use.
Q2.
$to_specialchars = true
is being used in a couple the function declarations as parameters. Setting it '=true' is just setting a default, so you could can do this:
echo $scrappy->getWebHtml('http://example.com');
Which is identical to this:
echo $scrappy->getWebHtml('http://example.com', true);
If you look at the return statement of that function, you'll see they are $to_specialchars is being checked, and if it's true, then the output is run through the PHP function htmlspecialchars() first.
Q3. If you look at the root of your codeigniter project, in index.php you'll see EXT defined as:
define('EXT', '.'.pathinfo(__FILE__, PATHINFO_EXTENSION));
and APPATH:
if (is_dir($application_folder))
{
define('APPPATH', $application_folder.'/');
}
else
{
if ($application_folder == '')
{
$application_folder = 'application';
}
define('APPPATH', BASEPATH.$application_folder.'/');
}
So these are two constants being set at bootstrapping, so you can use them in your application, and if you were to ever change them, then it wouldn't instances like where you see it being used in the code you provided.
Please next time have one question per stackoverflow question :)
. This sample Scraping code was written based on using the library:
"Snoopy - the PHP net client ( snoopy.sourceforge.net )"
I tried to post it again. but I couldn't post with hyperlinks. sorry..
I'll answer to that in my site.(I'm a newbie stackoverflow.com :-( )
I think that I'll try to repost these answers after a few days .
( http://d.hatena.ne.jp/dix3/20091004 )
Related
I've got two files, like these two:
<?php
session_start();
class test{
public function login($code){
$app = JFactory::getApplication('site');
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(array('id'))
->from($db->quoteName('#__users'))
->where($db->quoteName('code') . " = " . $db->quote($code));
$db->setQuery($query);//execute query
$results = $db->loadObjectList();//get results
if ($results[0] != null) {
$this->createSession($results[0]);
header("refresh:2;url=second_file.php");
}
return json_encode($results);
}
public function createSession($LoginInfo){
$_SESSION['userId']=$LoginInfo->id;
}
}
?>
and another php file like this:
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<?php
echo $_SESSION['userId'];
?>
</body>
</html>
In the second page seems like that there is no information inside the session and i'm unable to get "userId" parameter.
PS: the first class php file is called by another php file where there is something like this:
require_once('test.class.php');
$mainframe = new test
if ($_GET['code']!=null) echo $mainframe->login($_GET['code']);
Where am I doing wrong? thanks.
PPS: All those file are hosted inside altervista.org and there is Joomla CMS installed.
I have a problem. I writed OOP in php, but it does not work. It gives me blank result. I putted screenshots of my code and result of that code above. Please analyse these codes and help me, how I can solve it. By the way my php version is 5.3. I can upgrade or downgrade it if it is important. Thanks.
index.php
<?php include('class_library.php'); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OOP ilk dersim)</title>
</head>
<body>
<?php
$phpders = new adam();
$padisah = new adam();
//----------
$phpders -> set_ad('NurlanXp 1');
$padisah -> set_ad('NurlanXp 2');
//------------
echo "PhpDersden gelen: ".$phpders -> get_ad;
echo "<br>Padisahdan gelen: ".$padisah -> get_ad;
?>
</body>
</html>
class_library.php
<?php
class adam{
var $ad;
function set_ad($yeni_ad){
$this -> ad = $yeni_ad;
}
function get_ad(){
return $this -> ad;
}
}
?>
index.php, class_library.php and the result of the code. Screenshots.
All documents in the same folder.
You seems using $padisah -> get_ad but your adam class doesn't have any getter metod so you have to use like
$padisah -> get_ad();
You can find working example on https://eval.in/591811
In Turkish: get_ad kısmının sonunda parantez açıp, kapatırsan sorun çözülür. Adam class'ının içerisinde getter metodu yok. Yukarıda verdiğim linkte sonundaki parantezle sorunun çözüldüğünü görebilirsin.
this is Your class:
<?php
class adam {
private $ad;
public function get_ad() {
return $this->ad;
}
public function set_ad($ad) {
$this->ad = $ad;
return $this;
}
}
and inside of code:
$phpders = new adam();
$padishah = new adam();
$phpders->set_ad('NurlanXP 1');
$padishah->set_ad('NurlanXP 2');
and usage of get_ad:
echo 'phpdersden gelen: '.$phpders->get_ad().'<br/>';
echo 'padishahdan gelen: '.$padishah->get_ad().'<br/>';
(After solving the issue mentioned by "num8er" - calling method with () ...)
Try to give an absolute include path
<?php include('/complete/path/to/class_library.php'); ?>
or set an appropriate include path set_include_path() before. You can use $_SERVER['DOCUMENT_ROOT'] as a base to build a path.
I was coding PHP using controll based on adress and GET method with index.php?site=filename. Then i was including existing filename.php in content div. That was simply but effective. Also i has got notification div where i included file with data from database
I'm trying to get similar result in CodeIgniter
html
head
/head
body
div notification bar (always on top like Material)
div menu (slide from left also like Material)
div content (depended on controller and loaded view)
div footer (only /body /html)
/body
/html
by
public function __construct()
{
parent::__construct();
$this -> load -> view('notification ');
$this -> load -> view('menu ');
}
I want do send data from model to notification view but i can't do this in constructor. Also i dont want to load this same view in each controller's method. How should i do this? I dont expct ready solution, but some ideas, maybe pseudocode?
Or maybe this is only one solution like this? Loading all needed views in every methods? Really?
class news extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this -> load -> view('header');
}
public function index()
{
[...]//data from model
$this -> load -> view('notification',$Data);
$this -> load -> view('menu',$Permission);
$this -> load -> view('news',$Content);
}
[...]
I'm trying this (sorry for polish words):
controller
class uzytkownik extends CI_Controller
{
public function index()
{
$this -> load -> model('Uzytkownik_model');
$DaneLogo['Tytul'] = 'Dzie z życia';
$Dane = array(
'Naglowek' => $this -> load -> view('naglowek', NULL, TRUE),
'Logo' => $this -> load -> view('logo', $DaneLogo, TRUE),
'Lista' => $this -> Uzytkownik_model -> PobierzUzytkownikow(),
);
$this -> load -> view('uzytkownicy', $Dane);
}
view
echo $Naglowek;
echo $Tytul;
echo $Logo;
foreach ($Lista->result() as $Uzytkownik)
{
echo $Uzytkownik -> id.' ';
echo $Uzytkownik -> imie.' ';
echo $Uzytkownik -> nazwisko.'<br>';
}
working fine but...
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8"/>
</head>
<body>
<div id='logo' style='background-color: blue; wight: 100%; height: 40px;'>
<center> <!-- i want $Tytul HERE --></center>
</div>
Dzie z zycia<!-- NOT HERE -->1 Jan Kowalski<br>2 Adam Nowak<br>3 Alicja Marczak<br></div>
</body>
So I have my views split up basically between three (3) files:
-- Header file
$this->load->view('templates/header', $data);
-- Main Body file
$this->load->view('login_view', $data);
-- Footer file
$this->load->view('templates/footer', $data);
Now I just recently started building, but I've noticed it's really annoying to retype the header and footer on every controller to tell it to load. Is there a way to automatically load the header and footer view on every request?
I found an article long time ago, but i can't seem to find it now, basically the author, (which i forgot) override the showing of output. this method of output will access your views regarding the given controller/method and will try to search in your views directory automatically.
Use at your own risk
Application/core/MY_COntroller.php
----------------------------------------------------------------------------
class MY_Controller Extends CI_Controller
{
protected $layout_view = 'layouts/application'; // default
protected $content_view =''; //data
protected $view_data = array(); //data to be passed
public function __construct()
{
parent::__construct();
}
public function _output($output)
{
if($this->content_view !== FALSE && empty($this->content_view)) $this->content_view = $this->router->class . '/' . $this->router->method;
$yield = file_exists(APPPATH . 'views/' . $this->content_view . EXT) ? $this->load->view($this->content_view, $this->view_data, TRUE) : FALSE ;
if($this->layout_view)
{
$html = $this->load->view($this->layout_view, array('yield' => $yield), TRUE);
echo $html;
}
}
}
Application/views/layouts/layout.php
----------------------------------------------------------------------------
<html>
<head>
<title>master layout</title>
</head>
<body>
<!-- this variable yeild is important-->
<div><?=$yield;?></div>
</body>
</html>
This is what i use to create my template. Basically you need a directory structure as follows.
+Views
|+layouts
||-layout.php
the layout.php will serve as your master template
How to use?
extend the controller
class User Extends MY_Controller
{
public function create_user()
{
//code here
}
public function delete_user()
{
//use a different master template
$this->layout_view = 'second_master_layout';
}
public function show_user()
{
//pass the data to the view page
$this->view_data['users'] = $users_from_db;
}
}
Just create directory in your views and name it with the controller name i.e user then inside it add a file you named your method i.e create_user
So now your Directory structure would be
+Views
| +layouts
| |-layout.php
| |-second_master_layout.php
| +user
| |-create_user.php
Just Edit the code to give you a dynamic header or footer
Here is the simple example which i always do with my CI project.
Pass the body part as a $main variable on controller's function
function test(){
$data['main']='pages/about_us'; // this is the view file which you want to load
$data['something']='some data';// your other data which you may need on view
$this->load->view('index',$data);
}
now on the view load the $main variable
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php $this->load->view('includes/header');?>
<div id="body">
<?$this->load->view($main);?>
</div>
<?php $this->load->view('includes/footer');?>
</div>
</body>
</html>
In this way you can always use index.php for your all the functions just value of $main will be different.
Happy codeing
Using MY_Controller:
class MY_Controller extends CI_Controller {
public $template_dir;
public $header;
public $footer;
public function __construct() {
parent::__construct();
$template_dir = 'templates'; // your template directory
$header = 'header';
$footer = 'footer';
$this->template_dir = $template_dir;
$this->header = $header;
$this->footer = $footer;
}
function load_views ($main, $data = [], $include_temps = true) {
if ($include_temps = true) {
$this->load->view('$this->template_dir.'/'.$this->header);
$this->load->view($main);
$this->load->view('$this->template_dir.'/'.$this->footer);
} else {
$this->load->view($main);
}
}
}
Then load it like: $this->load_views('login_view', $data);
You can do with library.
Create a new library file called template.php and write a function called load_template. In that function, use above code.
public function load_template($view_file_name,$data_array=array()) {
$ci = &get_instatnce();
$ci->load->view("header");
$ci->load->view($view_file_name,$data_array);
$ci->> load->view("footer");
}
You have to load this library in autoload file in config folder. so you don't want to load in all controller.
You can call
$this->template->load_template("index",$data_array);
If you want to pass date to view file, then you can send via $data_array
There is an article on this topic on ellislab forums. Please take a look. It may help you.
http://ellislab.com/forums/viewthread/86991/
Alternative way: Load your header and footer views inside the concern body view file. This way you can have batter control over files you want to include in case you have multiple headers and footer files for different purposes. Sample code shown below.
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php $this->load->view('header');?>
<div id="body">
body
</div>
<?php $this->load->view('footer');?>
</div>
</body>
</html>
I am working in yii framework.I am getting stuck at a point where I have to call a function inside controller in yii framework from core php file. Actually I am going to create html
snapshot.
my folder structure is
seoPravin--
--protected
--modules
--kp
--Dnycontentcategoriescontroller.php
--DnycontentvisitstatController.php
--themes
--start.php (This is my customized file)
--index.php
1) Code of start.php file :--
<!DOCTYPE HTML>
<html>
<head>
<?php
if (!empty($_REQUEST['_escaped_fragment_']))
{
$yii=dirname(__FILE__).'/yii_1.8/framework/yii.php';
require_once($yii);
$escapeFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapeFragment);
include 'protected/components/Controller.php';
include 'protected/modules/'.$arr[0].'/controllers/'.$arr[1].'Controller.php';
echo DnycontentcategoriesController::actiongetDnyContent(); //gettting error at this point
?>
</head>
<body>
<?php
//echo "<br> ".$obj->actiongetDnyContent();
}
?>
</body>
</html>
2) yii side controller function : This function work for normal but when I am calling using escaped_fragment it gives error
public static function actiongetDnyContent()
{
if (!empty($_REQUEST['_escaped_fragment_']))//code inside if statement not working
{
$escapedFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapedFragment);
$contentTitleId=end($arr);
$model = new Dnycontentvisitstat(); //Error got at this line
}
else //Below code is working properly
{
$dependency = new CDbCacheDependency('SELECT MAX(createDateTime) FROM dnycontent');
$content = new Dnycontent();
$content->contentTitleId = $_GET['contentTitleId'];
$content = $content->cache(2592000,$dependency)->getContent();
$userId=105;
$ipAddress=Yii::app()->request->userHostAddress;
echo "{\"contents\":[".CJSON::encode($content)."]} ";
$model = new Dnycontentvisitstat();
$model->save($_GET['contentTitleId'], $userId, $ipAddress);
}
}
error:
Fatal error: Class 'Dnycontentvisitstat' not found in
C:\wamp\www\seoPravin\protected\modules\KnowledgePortal\controllers\DnycontentcategoriesController.php
on line 289
code is working for normal url but not working for _esaped_fragment
It is a very bad practice but you can do a HTTP self request, like this:
include("http://{$_SERVER['HTTP_HOST']}/path/?r=controller/action&_param={$_GET['param']}");
Check http://www.php.net/manual/en/function.include.php to see how to enable HTTP includes.