Friday, 14 December 2012

PHP - Web Services: Fetching Data From Database

PHP Web Services Tutorial: Now, we try fetch data from database at server side. Send to client as array format. Before read this post, we must understand about sending array format in nusoap. You can read it at here. If you still don't understand about php webservices, you can read this base article.

For practice, we will build simple database about book. Follow this steps:

    Open your phpmyadmin by pointing your browser to http://localhost/phpmyadmin.
    Create new database baru, named "testdb".

    Create new table, named "book".

    Fill fields of this table.

    Insert some example data. Click insert tab.

    Then, write & insert some example data.
    Now, create file named "server_book.php" within www/test/nusoap.

    Enter following code:
    01    <?
    02    //call library
    03    require_once ('lib/nusoap.php');
    04   
    05    //using soap_server to create server object
    06    $server = new soap_server;
    07   
    08    //register a function that works on server
    09    $server->register('getallbook');
    10   
    11    // create the function
    12    function getallbook()
    13    {
    14       $conn = mysql_connect('localhost','root','admin');
    15       mysql_select_db('testdb', $conn);
    16       
    17       $sql = "SELECT * FROM book";
    18       $q  = mysql_query($sql);
    19       while($r = mysql_fetch_array($q)){
    20         $items[] = array('cd'=>$r['cd'],
    21                              'title'=>$r['title'],
    22                              'author'=>$r['author'],
    23                           'publisher'=>$r['publisher']);
    24       }
    25       return $items;
    26   
    27    }
    28   
    29    // create HTTP listener
    30    $server->service($HTTP_RAW_POST_DATA);
    31   
    32    exit();
    33   
    34    ?>
    Create a file named "client_book.php" as client within www/test/nusoap. Enter following code:
    01    <?
    02    require_once ('lib/nusoap.php');
    03   
    04    $client = new soapclient('http://localhost:8048/test/nusoap/server_book.php');
    05   
    06    $response = $client->call('getallbook');
    07   
    08    if($client->fault)
    09    {
    10       echo "FAULT: <p>Code: (".$client->faultcode.")</p>";
    11       echo "String: ".$client->faultstring;
    12    }
    13    else
    14    {
    15       $r = $response;
    16       $count = count($r);
    17       ?>
    18        <table border="1">
    19        <tr>
    20           <th>Code</th>
    21           <th>Title</th>      
    22           <th>Author</th>      
    23           <th>Publisher</th>      
    24        </tr>
    25        <?
    26        for($i=0;$i<=$count-1;$i++){
    27       ?>
    28        <tr>
    29           <td><?=$r[$i]['cd']?></td>
    30           <td><?=$r[$i]['title']?></td>
    31           <td><?=$r[$i]['author']?></td>              
    32           <td><?=$r[$i]['publisher']?></td>      
    33        </tr>
    34        <?
    35       }
    36       ?>
    37        </table>
    38        <?
    39    }
    40    ?>

Now, point your browser to http://localhost/test/nusoap/client_book.php. You should get like this:

PHP - Web Services: Serving Data Array

PHP Web Services Tutorial: We ever talk about web services at here. In this post, we talk about how to create data array in server. Client will send two data: name and birthday. In the same time, client will fetch array ( name and age). It is realy simple.

I modify from our practice about web services. Create "server_array.php". Placed within (example) www/test/nusoap. Enter this codes:
01    <?
02     //call library
03     require_once ('lib/nusoap.php');
04   
05     //using soap_server to create server object
06     $server = new soap_server;
07   
08     //register a function that works on server
09     $server->register('hello');
10   
11     // create age calculation function
12     function find_age($birthday)
13     {
14          list($byear, $bmonth, $bday) = explode('-', $birthday);
15          list($cyear, $cmonth, $cday) = explode('-', date('Y-m-d'));
16        
17          $cday -= $bday;
18          $cmonth -= $bmonth;
19          $cyear -= $byear;
20        
21          if($cday < 0)
22          $cmonth--;
23          if($cmonth < 0)
24          $cyear--;
25        
26          return $cyear;
27     }
28   
29     // create the function
30     function hello($name,$birthday)
31     {
32   
33          if(!$name){
34                return new soap_fault('Client','','Put your name!');
35          }
36   
37      <b> $result = array('name'=>$name,'age'=>find_age($birthday));</b>
38          return $result;
39   
40     }
41   
42     // create HTTP listener
43     $server->service($HTTP_RAW_POST_DATA);
44     
45     exit();
46     
47     ?>

Now, this is client side. Create "client_side.php". Put within www/test/nusoap. Enter following codes:
01    <?
02    require_once ('lib/nusoap.php');
03   
04    $param = array( 'name' => 'Babablackship','birthday'=>'1980-12-24');
05   
06    $client = new soapclient('http://localhost:8048/test/nusoap/server_array.php');
07   
08    $response = $client->call('hello',$param);
09   
10    if($client->fault)
11    {
12        echo "FAULT: <p>Code: (".$client->faultcode.")</p>";
13        echo "String: ".$client->faultstring;
14    }
15    else
16    {
17        echo $response['name'];
18        echo "<br>";
19        echo "Age: ".$response['age']."'s";
20    }
21    ?>

Ok. Now, point your browser to http://localhost/nusoap/test/client_array.php. You must see like this:

Web Services: How PHP Kiss VB.NET? (Part 2)

After build server function (web services). Now we try to read the web service from VB.NET. It will give idea how to we develop multiplatform application.

For this tutorial, I use Microsoft Visual Studio 2003. For this tool, it can accept web services standar using WSDL (Web Services Describe Language). So we must create wsdl before.

Create "server_wsdl.php" within test/nusoap. Enter following code:
01     <?php
02     // call library
03     require_once ( 'lib/nusoap.php' );
04     
05     // create instance
06     $server = new soap_server();
07     
08     // initialize WSDL support
09     $server->configureWSDL( 'hellowsdl' , 'urn:hellowsdl' );
10     
11     // place schema at namespace with prefix tns
12     $server->wsdl->schemaTargetNamespace = 'urn:hellowsdl';
13     
14     // register methode
15     $server->register('hello', // method name
16       array('name'=>'xsd:string'),
17    // input parameter
18       array('return'=>'xsd:string'),// output
19       'urn:hellowsdl' ,// namespace
20       'urn:hellowsdl#hello',// soapaction
21       'rpc',// style
22       'encoded',// use
23       'Say hello to the caller'// documentation
24     );
25     
26     // define method as function
27     function hello($name)
28     {
29       return "Hello, ".$name;
30     }
31     
32     $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
33     
34     $server->service($HTTP_RAW_POST_DATA);
35     
36     ?>

Ok, now we try to open at VB.NET.

    Open your Microsoft Visual Studio 2003.
    File > New > Project. You will get dialog box. Choose visual basic projects at Project Types and Windows Application at Templates. Choose name and location where your application saved. Click OK button.

    Right click at Reference in Solution Explorer. Choose add web references.

    You will get dialog box.
    Put http://localhost:8048/test/nusoap/server_wsdl.php?wsdl at URL. You should get like this:

    Click Add Reference button. Your Solution explorer should like this:

    Put label, textbox, and button. Place like following screen.

    Double click botton. Add following code:
    1      Dim name As String
    2      name = TextBox1.Text
    3   
    4      Dim ws As New localhost.hellowsdl
    5      MsgBox(ws.hello(name))
    Press F5 for run.

Put a name at textbox, then click button. You will get message box like following screen:

It is simple, isn't it?

Web Services: How PHP Kiss VB.NET? (Part 1)

XML, SOAP, and multitier programming is amazing technology that make we can collaborate with other programmer building big size and complex application in multiplatforms. This technology make us more easy and more simple in complicated world.

This tutorial about connecting PHP with VB.NET using web services. Why I use VB.NET to explain web services in PHP? I just want to show one of function of web services, connecting multiplatform.

In php, we can use nusoap library to create web services. You can download this library at http://sourceforge.net/projects/nusoap/. In this tutorial use nusoap-0.7.3.

    Download nusoap library.
    Extract to web directory, example within C:\AppServ\www\test. Rename folder became "nusoap". So, you get structure like this:

    Now, we will create server function. Create "server.php" within C:\AppServ\www\test\nusoap. Enter following code:
    01    <?
    02    //call library
    03    require_once ('lib/nusoap.php');
    04   
    05    //using soap_server to create server object
    06    $server = new soap_server;
    07   
    08    //register a function that works on server
    09    $server->register('hello');
    10   
    11    // create the function
    12    function hello($name)
    13    {
    14      if(!$name){
    15        return new soap_fault('Client','','Put your name!');
    16      }
    17        
    18      $result = "Hello, ".$name;
    19      return $result;
    20    }
    21   
    22    // create HTTP listener
    23    $server->service($HTTP_RAW_POST_DATA);
    24   
    25    exit();
    26    ?>
    Now, it is time to test. Point your browser to http://localhost/test/nusoap/server.php. If work, you will get like following screen:

    After create server, now we will test this server function. Create "client.php" at test/nusoap. Enter following code:
    01    <?
    02    require_once ('lib/nusoap.php');
    03   
    04    //Give it value at parameter
    05    $param = array( 'name' => 'Babablackship');
    06   
    07    //Create object that referer a web services
    08    $client = new soapclient('http://localhost:8048/test/nusoap/server.php');
    09   
    10    //Call a function at server and send parameters too
    11    $response = $client->call('hello',$param);
    12   
    13    //Process result
    14    if($client->fault)
    15    {
    16      echo "FAULT: <p>Code: (".$client->faultcode."</p>";
    17      echo "String: ".$client->faultstring;
    18    }
    19    else
    20    {
    21      echo $response;
    22    }
    23    ?>

Now, point your browser to http://localhost/test/nusoap/client.php. You should see:
You can change value of parameter at line 5. But if value is nothing, it raise error message. Next tutorial, we will try to read the web services from VB.NET. Don't miss it!

PHP - XML: Filtering XML Nodes by Namespace

PHP XML Tips - Part 11: Do you want to find only those nodes belonging to a particular namespace? You can look solution like this:
01    <?php
02    $xmlString = <<< END
03    <?xml version="1.0"?>
04    <data xmlns:home="http://www.mysite.com/xmlns/home" xmlns:pdf="http://www.mysite.com/xmlns/work">
05      <home:file>content1.doc</home:file>
06      <pdf:file>content2.pdf</pdf:file>
07      <pdf:file>content3.pdf</pdf:file>
08      <home:file>content4.txt</home:file>
09      <home:file>content5.rtf</home:file>
10      <pdf:file>content6.pdf</pdf:file>      
11    </data>
12    END;
13   
14    $xml  = simplexml_load_string($xmlString);
15   
16    foreach($xml->children("http://www.mysite.com/xmlns/work") as $file){
17      echo $file ." <br />";
18    }
19    ?>

Result like this:
1    content2.pdf
2    content3.pdf
3    content6.pdf

PHP - XML: Filtering XML Nodes with XPath

PHP XML Tips - Part 10: Do you want to show text from particular nodes? You can use XPath to filter XML nodes. Like this:
1    <?php
2    $xml = simplexml_load_file("books.xml")
3           or die("Error: Cannot create object");
4    // we want to show just <title> nodes
5    foreach($xml->xpath('//title') as $title){
6      echo $title. "<br />";
7    }
8    ?>

Books.xml, you can see at this.

Result, like this:

PHP - XML: Replacing Node

PHP XML Tips - Part 9: Do you want to replace a node in XML? You can use replaceChild() like this:
01    <?php
02    $file = "books.xml";
03    $fp = fopen($file, "rb") or die("cannot open file");
04    $str = fread($fp, filesize($file));
05   
06   
07           
08    $xml = new DOMDocument();
09    $xml->formatOutput = true;
10    $xml->preserveWhiteSpace = false;
11    $xml->loadXML($str) or die("Error");
12   
13    // original
14    echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
15   
16    // get document element
17    $root   = $xml->documentElement;
18    $fnode  = $root->firstChild;
19   
20    //get a node
21    $ori    = $fnode->childNodes->item(1);
22   
23    $id     = $xml->createElement("id");
24    $idText = $xml->createTextNode("3");
25    $id->appendChild($idText);
26   
27    $title     = $xml->createElement("title");
28    $titleText = $xml->createTextNode("PHP Framework");
29    $title->appendChild($titleText);
30   
31    $author     = $xml->createElement("author");
32    $authorText = $xml->createTextNode("Reza Christian");
33    $author->appendChild($authorText);
34   
35    $book   = $xml->createElement("book");
36    $book->appendChild($id);
37    $book->appendChild($title);
38    $book->appendChild($author);
39   
40    $fnode->replaceChild($book,$ori);
41   
42    echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
43    ?>

Books.xml, you can see at this.

Result, like this


PHP - XML: Removing Node

PHP XML Tips - Part 8: Do you want to remove child from exist XML? You can use removeChild(). Look at this:
01    <?php
02    $file = "books.xml";
03    $fp = fopen($file, "rb") or die("cannot open file");
04    $str = fread($fp, filesize($file));
05   
06   
07           
08    $xml = new DOMDocument();
09    $xml->formatOutput = true;
10    $xml->preserveWhiteSpace = false;
11    $xml->loadXML($str) or die("Error");
12   
13    // original
14    echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
15   
16    // get document element
17    $root   = $xml->documentElement;
18    $fnode  = $root->firstChild;
19   
20    //get a node
21    $ori    = $fnode->childNodes->item(1);
22   
23    // remove
24    $fnode->removeChild($ori);
25   
26    echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
27    ?>

Books.xml, you can see at this.

Result, like this:

PHP - XML: Adding XML Nodes

PHP XML Tips - Part 7: Do you want add nodes to exist XML? Ok, I will show to you. Look at this example:
01    <?php
02    $file = "books.xml";
03    $fp = fopen($file, "rb") or die("cannot open file");
04    $str = fread($fp, filesize($file));
05   
06   
07           
08    $xml = new DOMDocument();
09    $xml->formatOutput = true;
10    $xml->preserveWhiteSpace = false;
11    $xml->loadXML($str) or die("Error");
12   
13    // original
14    echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
15   
16    // get document element
17    $root   = $xml->documentElement;
18    $fnode  = $root->firstChild;
19   
20    //add a node
21    $ori    = $fnode->childNodes->item(2);
22   
23    $id     = $xml->createElement("id");
24    $idText = $xml->createTextNode("3");
25    $id->appendChild($idText);
26   
27    $title     = $xml->createElement("title");
28    $titleText = $xml->createTextNode("PHP Framework");
29    $title->appendChild($titleText);
30   
31    $author     = $xml->createElement("author");
32    $authorText = $xml->createTextNode("Reza Christian");
33    $author->appendChild($authorText);
34   
35    $book   = $xml->createElement("book");
36    $book->appendChild($id);
37    $book->appendChild($title);
38    $book->appendChild($author);
39   
40    $fnode->insertBefore($book,$ori);
41   
42    echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
43    ?>

First, you must have a xml document named "books.xml". You can see at this.

After run it, you may get like this:
XML - add nodes
XML - add nodes

PHP - XML: Creating XML Document

PHP XML Tips - Part 6: You can make a xml document with easy. Look example:
01    <?php
02   
03    $xml = new DOMDocument("1.0");
04   
05    $root = $xml->createElement("data");
06    $xml->appendChild($root);
07   
08    $id   = $xml->createElement("id");
09    $idText = $xml->createTextNode('1');
10    $id->appendChild($idText);
11   
12    $title   = $xml->createElement("title");
13    $titleText = $xml->createTextNode('"PHP Undercover"');
14    $title->appendChild($titleText);
15   
16   
17    $book = $xml->createElement("book");
18    $book->appendChild($id);
19    $book->appendChild($title);
20   
21    $root->appendChild($book);
22   
23    $xml->formatOutput = true;
24    echo "<xmp>". $xml->saveXML() ."</xmp>";
25   
26    $xml->save("mybooks.xml") or die("Error");
27   
28    ?>

PHP - XML: Processing XML

PHP XML Tips - Part 5: If you want to recursively process and XML document. You can create a function like this:
01    <?php
02    $xml = simplexml_load_file("books.xml")
03           or die("Error: Cannot create object");
04   
05    function processXML($node){
06      foreach($node->children() as $books => $data){
07        if(trim($data) != ""){
08          echo $books.": ".$data;
09          echo "<br />";
10        }
11        processXML($data);
12      }
13    }
14           
15    processXML($xml);
16   
17    ?>

We can write a function to parse object. If we dont find node value, we recall again function.

PHP - XML: Retrieving Attribute Values

PHP XML Tips - Part 4: Below, sample how to retrieve attribute value.

First, create xml document like this:
01    <?xml version="1.0"?>
02    <datas>
03      <cars>
04        <car>
05          <manufacture country="japan">Honda</manufacture>
06          <type>Honda Jazz</type>
07        </car>
08        <car>
09          <manufacture country="korea">Nissan</manufacture>
10          <type>Nissan Livina</type>
11        </car>  
12      </cars>
13    </datas>

Save as "cars.xml" within www/test/xml. Then create reader like this:
01    <?php
02    $xml = simplexml_load_file("cars.xml")
03           or die("Error: Cannot create object");
04           
05    foreach($xml->children() as $cars){
06        foreach($cars->children() as $car => $data){
07          echo $data->manufacture['country'];
08          echo "<br />";
09        }
10    }
11   
12    ?>

As you see, to read attribute value, we can use such as $data->manufacture['country'].

PHP - XML: Retrieving Node Values

PHP XML Tips - Part 3: Read node values use simplexml is very easy. Look at this sample:
01    <?php
02    $xml = simplexml_load_file("books.xml")
03           or die("Error: Cannot create object");
04           
05    foreach($xml->children() as $books){
06        foreach($books->children() as $book => $data){
07          echo $data->id;
08          echo $data->title;
09          echo $data->author;
10          echo "<br />";
11        }
12    }
13   
14    ?>

You can write books.xml like in this post.

PHP - XML: Read from a File

PHP XML Tips - Part 2: This post show to us how to read xml from a file. We can use simplexml_load_file() file this:
1    <?php
2    $xml = simplexml_load_file("books.xml")
3           or die("Error: Cannot create object");
4   
5    ?>

Before test it, create a file named "books.xml".
01    <?xml version="1.0"?>
02    <datas>
03      <books>
04        <book>
05          <id>1</id>
06          <title>PHP Undercover</title>   
07          <author>Wiwit Siswoutomo</author>
08        </book>
09        <book>
10          <id>2</id>
11          <title>PHP Enterprise</title>   
12          <author>Wiwit Siswoutomo</author>
13        </book>
14      </books>
15    </datas>

PHP - XML: Read from String

PHP XML Tips - Part 1: If you have a variable contains XML data, you can read/parse like this:
view source
print?
01    <?php
02    $xmlData =<<< END
03    <?xml version="1.0"?>
04    <datas>
05      <books>
06        <book>
07          <id>1</id>
08          <title>PHP Undercover</title>   
09          <author>Wiwit Siswoutomo</author>
10        </book>
11      </books>
12    </datas>
13    END;
14   
15    $xml = simplexml_load_string($xmlData)
16           or die("Error: Can not create object");
17   
18    ?>

Yes, we can use simplexml_load_string() function.

Thursday, 6 December 2012

php code for reading WCF service


try{

//url of service
  $client = new SoapClient("http://mmadtime360.azurewebsites.net/TrackService.svc?wsdl");

// Set parameters

$parms['MobileNumber'] = '8095150424';
$parms['TrackingDate'] = '12/04/2012';

// Call web service PassMember methordd
 $webService = $client->GetTrackingInfo($parms);


// print response
 print_r($webService);
      
       } catch (Exception $e) {
       echo 'Caught exception:',  $e->getMessage(), "\n";
}