tags:

views:

56

answers:

2

I have a form that looks like this. Now a client has asked to convert this to a format that queries and sends response in XML. Can someone pint me to appropriate tutorial or example in PHP. There seems to be many ways of doing this

<form action="" method='post'>
<table>
<tr><td>User Number </td><td><input type='text' name='task_user_no' value='<?=$task_user_no?>'></td></tr>
<tr><td>Date </td><td><input type='text' name='task_date' value='<?=$task_date?>'> (YYYYMMDD)</td></tr>
<tr><td>From Time </td><td><input type='text' name='task_from_time' value='<?=$task_from_time?>'>(HHMM)</td></tr>
<tr><td>To Time </td><td><input type='text' name='task_to_time' value='<?=$task_to_time?>'>(HHMM)</td></tr>
<tr><td>Message </td><td><input type='text' name='task_message' value='<?=$task_message?>'></td></tr>
<tr><td>&nbsp;</td><td><input type='submit' value='submit' name='submit' ></td></tr>
</form>
A: 

Take a look at Jquery Ajax Function

Doc

Elliott
I don't think I want an ajax response. Ultimatlely, we wan to get rid of form and have remote server make automated queries on our server. I need a PHP solution to make and respond to XML requests. (Is it my imagination or has jQuery become the answer to half the questions asked here?)
hank williams
haha it's not your imagination, about your question I don't know how you can send the data from php to xml. Won't be too long until a expert comes along :)
Elliott
+1  A: 

Well since you havent provided details ill lay down the basics:

  1. A cron job, user interaction, or some other trigger invokes the request on the Remote Server (RS)
  2. The php script on the RS builds a query to send to the Application Server (AS) that hosts your site/application
  3. The AS parses the request variables and builds a query for the data store.
  4. The AS makes the query on data store, and transforms the results to an XML format
  5. The AS sends the response as XML to the RS
  6. The RS parses the XML and does whatever it needs to do with the data it contains

So given these steps some example scripts:

RS Server Script

// set up params for query:

$params = array(
  'task_no' => '0000000'
  'task_date' => 'YYYYMMDD',
  'task_from_time' => 'HHMM',
  'task_to_time' => 'HHMM',
  'taks_message' => 'The Message'
);

$client = curl_init('http://remote-server.com/task.php');

// return the response instead of outputting it
curl_setopt($client, CURLOPT_RETURNTRANSFER, true); 

// make it a POST request, use CURLOPT_GET for Get requests
curl_setopt($client, CURLOPT_POST, true);

// set the data to send.. if using get then intstead use http_build_query($params) and append the resuult to the URL used in curl_init
curl_setopt($client, CURLOPT_POSTFIELDS, $params);

$response = curl_exec($client);

// load the response as xml

try
{
  $responseXml = new SimpleXmlElement($response);

  // do stuff here with the result see SimpleXml documentation for working with the xml nodes

  exit;
}
catch(Exception $e)
{
   // log message from exception

   // exit with a non-zero status code may be important for cron or a shell invocation
   exit($e->getCode()); 
}

task.php script on the AS

// Im going to use PDO for simplicity sake
$db = new PDO($dsn, $user, $pass);
$query = 'SELECT * from table_name'
         .'WHERE task_user_no = :task_user_no' 
         .'AND task_date = :task_date' 
         .'AND task_from_time = :task_from_time'
         .'AND task_to_time = :task_to_time';

$stmt = $db->prepare($query);
$params = $_POST; // make a copy for binding
$xml = new DOMDocument('1.0', 'UTF-8');

// create some basic elements
$response = $xml->createElement('response');
$info = $xml->createElement('info');
$results = $xml->createElement('results');

// set up an array we can append later if there are errors
$errors = array();

foreach($params as $field => $value)
{
   $paramName = ':' . $field;

   switch($field)
   {
      case 'task_user_no':
        $paramType = PDO::PARAM_INT; // assuming an int pk/fk
        break;
      default:
        $paramType = PDO::PARAM_STR; // assuming string for all others
        break;
   }

   if(!$stmt->bindParam($paramName, $param[$field], $paramType))
   {

       $errors[] = $xml->createElement('error', sprintf(
          'Value for (%s) does not exist or is not of the proper type (%s).'
           $field,
           $paramType
       ));
   }
}

if(!$stmt->execute() && ($pdoError = $stmt->errorCode()))
{
   $errors[] = sprintf(
      'There was an error retrieving your data, Error (%s)',
      $pdoError
    );
}


while(false !== ($record = $stmt->fetch(PDO::FETCH_ASSOC)))
{
  $task = $xml->createElement('task');

  foreach($record as $col => $val)
  {
    $task->appendChild($xml->createElement($col, $val));

    $results->appendChild($task);
   }
}

if(!empty($errors))
{
   $errorsElement = $xml->createElement('errors');

   foreach($errors as $error)
   {
      $errorsElement->appendChild($xml->createElement('error', $error));
   }

  $info->appendChild($errorsElement);
}

$response->appendChild($info);
$response->appendChild($results);
$xml->appendChild($response);

$responseStr = $xml->saveXml();

header('Content-type: text/xml');
header('Content-length: '. strlen($responseStr));
header('HTTP/1.1 200 Ok');
print $responseStr;
exit;

Of course you can use existing libraries to further simplicty things... For example instead of using curl you could use Zend_Http_Client (which i would definitely recommend since it not only allows you to use curl but also fopen and direct sockets). OR for the xml response parsing on the AS you could use Zend_Dom_Query which basically allows you to work with the xml response in a way similar to jQuery (css selectors and what not instead of xPath).

prodigitalson
a great tutorial. Thanks!
hank williams