Skip to main content

Posts

Showing posts from 2009

SimpleXML does not parse text inside CDATA tags in an XML.

SimpleXML does not parse text inside CDATA tags in an XML.

Consider the XML below:


$str = '';
$str.='some text goes here';
$str.='';

To parse it we use following syntax:

$xml = simplexml_load_string($str);

On printing it outputs:


SimpleXMLElement Object
(
[childNode] => some text goes here
)

Thats OK. Now the same xml but this time the text is enclosed in CDATA tags.


$str = '';
$str.='';
$str.=''

On printing this gives following output:


SimpleXMLElement Object
(
[childNode] => SimpleXMLElement Object
(
)

)

Yes its empty. This is because SimpleXML does not parse CDATA tags. All data enclosed within CDATA is ignored by SimpleXML parser.
Solution: Set the 3rd parameter to LIBXML_NOCDATA while parsing.

simplexml_load_string(simplexml_load_file too) actually takes 3 parameters.

* The string to parse
* Optional parameter – to return an object of class specified in this parameter. (By default it returns a SimpleXMLElement Object)

Find how many number of result of your site on google

<?php
/* return result number */
function get_google_results($domain = 'vijayjoshi.org')
{
// get the result content
$content = file_get_contents('http://www.google.com/search?q=site:'.$domain);

// parse to get results
$result = get_match('/Results <b>(.*)from/isU',$content);

// echo $result;

// split the results
$split1 = explode('of about',$result);

// return result
return $split1[1] ? strip_tags($split1[1]) : 0;
}

/* helper: does the regex */
function get_match($regex,$content)
{
preg_match($regex,$content,$matches);
return $matches[1];
}

/* do it! */
echo 'vijayjoshi.org: '.get_google_results('vijayjoshi.org'); // 164
//echo 'Philogy.com: '.get_google_results('philogy.com'); // 164
?>

How to upload file with FTP in PHP

<?php
/*
***************************************************************************************

***************************************************************************************
*/
prepare a form similiar to this and have it call the below file
echo '<form action="image_upload.php" method="post" enctype="multipart/form-data">';
echo 'Click the Browse button to find the file you wish to upload';
echo '<input type="file" name="imagefile">';
echo '<INPUT TYPE="submit" name="upload" value="upload">';
echo '</form>';
/**************************************************************************************
***************************************************************************************
***************************************************************************************
*** <input type="file" name=&…

Creates a backup of a MySQL in SQL format.

<?
if(!$res=mysql_connect('localhost','root',''))
{
echo "Error1";exit;
}

if(!$db=mysql_select_db('vision_old'))
{
echo "Error2";exit;
}
if (!function_exists('mysql_dump')) {
function mysql_dump1($database) {
$query = '';
$tables = @mysql_list_tables($database);
while ($row = @mysql_fetch_row($tables)) { $table_list[] = $row[0]; }
for ($i = 0; $i < @count($table_list); $i++) {
$results = mysql_query('DESCRIBE ' . $database . '.' . $table_list[$i]);
$query .= 'DROP TABLE IF EXISTS `' . $database . '.' . $table_list[$i] . '`;' . lnbr;
$query .= lnbr . 'CREATE TABLE `' . $database . '.' . $table_list[$i] . '` (' . lnbr;
$tmp = '';
while ($row = @mysql_fetch_assoc($results)) {
$query .= '`' . $row['Field'] . '` ' . $row['Type'];
if ($row['Null']…

Mysql function run in the environment of PHP

Mysql function run in the environment of PHP
mysql_affected_rows — Get number of affected rows in previous MySQL operationmysql_change_user — Change logged in user of the active connectionmysql_client_encoding — Returns the name of the character setmysql_close — Close MySQL connectionmysql_connect — Open a connection to a MySQL Servermysql_create_db — Create a MySQL databasemysql_data_seek — Move internal result pointermysql_db_name — Get result datamysql_db_query — Send a MySQL querymysql_drop_db — Drop (delete) a MySQL databasemysql_errno — Returns the numerical value of the error message from previous MySQL operationmysql_error — Returns the text of the error message from previous MySQL operationmysql_escape_string — Escapes a string for use in a mysql_querymysql_fetch_array — Fetch a result row as an associative array, a numeric array, or bothmysql_fetch_assoc — Fetch a result row as an associative arraymysql_fetch_field — Get column information from a result and return as an objec…

Lower Case an Array

Lower Case an Array

Here is an example of how to force all values in array tolower case. This could, of course, be used in the same way to make the array UPPERCASE or do anything else you wish to the array values. Note the that the string is passed to the array by reference. This is so the actual array values are manipulated.

<?php

/*** an array of mixed case words ***/
$array = array('MAC', 'Apple', 'osX');

/**
*
* @Lower case an array
*
* @param ref string $string
*
* @return string
*
*/
function lower(&$string){
$string = strtolower($string);
}

/*** apply the lower function to the array ***/
array_walk($array,'lower');

foreach($array as $value){
echo $value;
}
?>

PHP SCRIPT-- TO TIME OUT THE SESSION AFTER THE PARTICULAR TIME [SESSION TIME OUT]

<?php
if (!isset($_SESSION['timeout_idle'])) {
$_SESSION['timeout_idle'] = time() + MAX_IDLE_TIME; //set time at the first time of writing script
} else {
if ($_SESSION['timeout_idle'] < time()) {
//destroy session if session time is less the what we have set the time
} else {
$_SESSION['timeout_idle'] = time() + MAX_IDLE_TIME; // if continue working on similar site then increase the time of script
}
}
?>

SEO CONCEPT--GET META TAG IN ARRAY-- SUPPORTED BY PHP

<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author']; // name
echo $tags['keywords']; // documentation
echo $tags['description']; // discription
echo $tags['geo_position']; // 49.33;-86.59

var_dump($tags); // get all values

?>

Secure file download from PHP server

< ?php
// local file that should be send to the client
$local_file = 'filename';
// filename that the user gets as default
$download_file = 'if_u_wanna_to_change_file_name_i._e._uploade_then name';
// I u do not want to change name then wrtre
//$download_file = 'if_u_wanna_to_change_file_name_i._e._uploade_then name';


// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file)) {
// send headers
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);

// flush content
flush();
// open file stream
$file = fopen($local_file, "r");
while(!feof($file)) {

// send the current file part to the browser
print fread($file, round($download_rate * 1024));

// flush the content to the browser
flush();

PHP5 Tutorial - Defining Attributes of a PHP5 Class

In this tutorial you will learn about class attributes and how to declare & use them in PHP5 classes. Definition of an class attribute
An attribute is also know as data members and is used to hold data of a class. The data that it holds are specific to the nature of the class in which it has been defined. For example, a Customer class would hold data related to a customer, an Order class would hold data related a an order.
Defining an attribute is as easy as declaring a variable within the body of the class. At the time of declaring a data member/variable within the body of the class, it is also possible to assign a default value to the attribute or data member.Attributes can either be public, private or protected - the default being public. These are called Access Specifiers. You will learn more about access specifiers in PHP5 OOPS tutorials ahead.Example Code:class Customer {
private$first_name, $last_name;
private$outstanding_amount = 0; //example of default value

publicfunction get…

PHP5 Tutorial - Learn to Create a PHP5 Class Object

In the earlier PHP5 OOPS tutorial you learnt how to create a class in PHP5. In this tutorial you will learn how to create an object of a PHP5 class. But before we begin, lets understand what is an object.Definition of an Object
An object is a living instance of a class. This means that an object is created from the definition of the class and is loaded in memory. A good analogy to understand this is to compare objects with humans - and understand that all of us (you and I) are objects. If God wants to send a human to earth, what is easy for Him to do? Create and define properties and attributes of each human separately or create a one time template and generate objects out if it. Therefore, this onetime template is a Class and you, I & everyone in this world is an object - that is a living instance of class Human.
Creating Objects in PHP5 ClassTo create an object of a PHP5 class we use the keyword new. Below is the syntax style of how to create objects in PHP5:$obj_name = new ClassN…

PHP5 Tutorial OOPS - PHP5 Class Access Specifiers - public, private and protected

In the earlier tutorials we have witnessed keywords like public, private and protected. These are nothing but access specifiers. So, lets understand what access specifiers are.Definition of Access Specifiers
Access specifiers specify the level of access that the outside world (i.e. other class objects, external functions and global level code) have on the class methods and class data members. Access specifiers can either be public, private or protected.
Why do we need Access specifiers
Access specifiers are used as a key component of Encapsulation and Data Hiding. By using either of the access specifiers mentioned above i.e. public, private or protected you can hide or show the internals of your class to the outside world.Explanation of each access specifier1. Private
2. Protected
3. Public
1. Private
A private access specifier is used to hide the data member or member function to the outside world. This means that only the class that defines such data member and member functions have access…

PHP5 Tutorial - Learn to create a PHP5 Class http://phpmysqlquestion.blogspot.com/

Before we begin learning how to create PHP5 Class, lets first understand the meaning of a class in object oriented programming practices.
Definition of a Class
A class is user defined data type that contains attributes or data members; and methods which work on the data members. (You will learn more about data members and methods in following tutorials. This tutorial focuses only on learning how to create a Class in PHP5)To create a class, you need to use the keyword class followed by the name of the class. The name of the class should be meaningful to exist within the system (See note on naming a class towards the end of the article). The body of the class is placed between two curly brackets within which you declare class data members/variables and class methods.
Following is a prototype of a PHP5 class structureclass{

;

}

Example of a Class:class Customer {
private$first_name, $last_name;

publicfunction getData($first_name, $last_name){
$this->first_name = $first_name;
$this->last_name…

PHP Interview Questions

PHP Interview Questions 1. What are the differences between GET and POST methods in form submitting, give the case where we can use get and we can use post methods?On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.2. Who is the father of php and explain the changes in php versions?Rasmus Lerdorf for version changes go to http://php.net/ Marco Tabini is the founder and publisher of php|architect.3. How can we submit from without a submit button?We can use a simple JavaScri…

PHP date difference

If you want to get the difference between to dates or time values, then you first need to get the values in the same format. The best way is to convert both dates into Unix timestamp format. In this case the date and time information is stored as an integer so we can calculate the difference easily. You can get the Unix timestamp in various ways as you can see below:<?php
// Get current time
$date1 = time();
// Get the timestamp of 2006 October 20
$date2 = mktime(0,0,0,10,20,2006);
? >

Now as you have the values getting the difference is quite easy. However the result will be an integer value, but you probably want to get it in days, hours and minutes. To do so we need to convert back our int value into a usable date format. We know that the difference is in seconds so we can get how many full days it is. To get it we use the following code:
&lt; ?php
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
echo"Differernce is $fullDays days";
?>

We used the fl…

Thumbnail photo/image format .jpg, .gif, .png in PHP at the time of image upload

<?php
//define a maxim size for the uploaded images
define ("MAX_SIZE","2048");
// define the width and height for the thumbnail
// note that these dimensions are considered the maximum dimension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","150");
define ("HEIGHT","100");

// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);

if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);

if(!strcmp("gif",$ext))
$src_img=imagecreatefromgif($img_na…