dongqiongzheng0615 2010-09-26 22:29
浏览 27
已采纳

html表单到XML响应和回复

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>
  • 写回答

2条回答 默认 最新

  • dongxuxian1123 2010-09-27 19:06
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面