Tuesday, April 27, 2010

Using PHP Dom to manipulate XML

PHP5 provides easy functions to access and manipulate xml.
SimpleXML and DOM.

SimpleXML sacrifices so many functionalities for simplicity.
This is a trade-off for the power and flexibility it provides.
You cannot remove and manipulate elements using simplexml directly.
But we can do the same using DOM. Also we can export simplexml objects to dom
and do the required modification. This is a pretty good feature.

Loading and Saving XML Documents:

There are two ways for loading xml documents.
First by loading from a file and second from string.

From File :

// PHP Script
<?php
$dom = new DOMDocument();
$dom->load("library.xml");
echo $dom->saveXML();
?>

//XML - Create a file library.xml and paste the following xml to it.

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

From string

// PHP Script
<?php
$xml = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML;
?>

Saturday, March 27, 2010

Extracting username from email address

Usually we extract username using a combination of functions. Let me show you the example.

1. Using substr_replace() and strpos:
<?php
$email = 'vijithbk@gmail.com';
echo substr_replace($email, "", strpos($email, "@"));
?>
// Output
vijithbk

2. Using strstr => this is available php 5.3.1+
<?php
$email = 'vijithbk@gmail.com';
echo strstr($email,"@",true);
?>
// Output
vijithbk

Is that simple??
if you have got some other simple methods dnt forget to post it as comments

Sunday, September 16, 2007

php strtok( ) function

Hi, its been a lot of time I have been working in php. Although i had been using this function for a long time I was quite unaware about its importance. This made me put a post about this nice function.

strtok() splits a string into smaller strings usually called as tokens, with each token being delimited by any character from token. That is, if you have a string like "This is vijithbk" you could tokenize this string into its small words by using the space character as the token.


$string = "This is vijith";

$tok = strtok($string, " ");

while (
$tok !== false)
{
echo
"Word=$tok \n";
$tok = strtok(" ");
}
//Output

Word=This Word=is Word=vijith