PHP

How To Write A Simple PHP Web Service

Web Services are Everywhere!
Let’s see how easy it is to create one using PHP, MySQL and XML!

First of all create a mysql database named notes.

Add a table named notes too:

CREATE TABLE IF NOT EXISTS `notes` (
  `ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `Title` VARCHAR(50) COLLATE utf8_unicode_ci NOT NULL,
  `Note` VARCHAR(500) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `Title` (`Title`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Add some values into this table!

Create a folder inside apache htdocs directory and name it webservice.
Create a file in webservice folder and name it index.php.
Open index.php for edit and paste the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$numofnotes = isset($_GET['num']) ? intval($_GET['num']) : 5;
$format = 'xml';
 
$connection = @mysql_connect('localhost', 'root', '*********') or die(mysql_error());
@mysql_select_db('notes', $connection) or die(mysql_error());
 
$query = 'SELECT * FROM notes LIMIT '.$numofnotes.';';
$result = @mysql_query($query, $connection) or die(mysql_error());
 
$notes = array();
if(@mysql_num_rows($result)) {
while($note = @mysql_fetch_assoc($result))
  $notes[] = array('note' => $note);
}
 
header('Content-type: text/xml');
echo '<notes>';
foreach($notes as $note) {
    foreach($note as $key => $value) {
      echo '<'.$key.'>';
      foreach($value as $tag => $val)
        echo '<'.$tag.'>'.htmlentities($val).'</'.$tag.'>';
      echo '</'.$key.'>';
    }
}
echo '</notes>';
 
@mysql_close($connection);

Open http://localhost/webservice in your browser.