【问题标题】:Cleaning xml data using str_ireplace function使用 str_ireplace 函数清理 xml 数据
【发布时间】:2017-07-11 04:13:30
【问题描述】:

当我运行脚本时,它会在数据库中存储空白。我哪里错了。下面是php脚本:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$request= <<<XML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:c2b="http://cps.huawei.com/cpsinterface/c2bpayment">
<soapenv:Header/>
<soapenv:Body>
  <c2b:C2BPaymentValidationRequest>
     <TransactionType>PayBill</TransactionType>
     <TransID>1234560000007031</TransID>
     <TransTime>20140227082020</TransTime>
     <TransAmount>123.00</TransAmount>
     <BusinessShortCode>12345</BusinessShortCode>
<BillRefNumber></BillRefNumber>
     <InvoiceNumber></InvoiceNumber>
<MSISDN>254722703614</MSISDN>
     <KYCInfo>
  <KYCName>[Personal Details][First Name]</KYCName>
  <KYCValue>Hoiyor</KYCValue>
</KYCInfo>
<KYCInfo>
  <KYCName>[Personal Details][Middle Name]</KYCName>
  <KYCValue>G</KYCValue>
</KYCInfo>
<KYCInfo>
  <KYCName>[Personal Details][Last Name]</KYCName>
  <KYCValue>Chen</KYCValue>
</KYCInfo>
  </c2b:C2BPaymentValidationRequest>
</soapenv:Body>
</soapenv:Envelope>
 XML;
//clean the soap input received from Mpesa so that you can parse it as raw XML

$clean_xml = str_replace(['soapenv:','c2b:' ],'', $request);
$xml = simplexml_load_string($clean_xml);
//you can extract any payment details using the below code
$server = '';
$user = '';
$pass = '';
$db  = ''; 

 foreach ($xml as $key => $cur)

 {
 //VALUES
  $AccountNo = $cur->BillRefNumber;
   $TransAmount = $cur->TransAmount;
  $TransID = $cur->TransID;
  $KYCInfo = $cur->KYCInfo;
  $MSISDN = $cur->MSISDN;                                                                                       

//SAVE TO DATABASE
$link= mysql_connect($server,$user,$pass) or die (mysql_error());
$conn= mysql_select_db($db) or die (mysql_error($link));                                                                                                
$query = "INSERT INTO c2b(TransID,MSISDN,BillRefNumber,KYCInfo,Amount) VALUES('$TransID','$MSISDN','$AccountNo','$KYCInfo','$TransAmount')";

if (!mysql_query($query))
{
die('Error: ' . mysql_error());
}
else
{
echo "New Records added successfully ! <br /><br />";       
}   
}                                                                                                                  

?>

我怀疑错误在于使用 str_ireplace 函数解析 xml 数据。我查看了 PHP 文档,似乎我已经按照书本完成了所有工作。

【问题讨论】:

  • 出于许多原因,您不应再使用 mysql_* 函数。如果您从教程中复制了此代码,那么寻找另一个可能是个好主意。
  • 您考虑过看看生成的 SQL 代码吗?
  • 我想我之前的评论不清楚。在$query = ... 行之后添加var_dump($query);,然后按Ctrl+U 以查看原始输出。
  • @ÁlvaroGonzález 这是我得到的答案string(82) "INSERT INTO c2b(TransID,MSISDN,BillRefNumber,KYCInfo,Amount) VALUES('','','','','')"
  • 瞧!您刚刚从调查中丢弃了一半的代码;-)

标签: php mysql xml-parsing


【解决方案1】:

我建议你在这些时候使用 PDO:

$link= mysql_connect($server,$user,$pass) or die (mysql_error());
$conn= mysql_select_db($db) or die (mysql_error($link));

我建议这个

class systemConfigs{
     public $conn;

     private $DBhost = 'localhost';
     private $DBname = 'mydbname';
     private $DBuser = 'dbuser';
     private $DBpwd  = 'dbpass';

     function __construct(){
        $this->dbConnect();
     }

     private function dbConnect(){
        $conn = null;
        try{
              $this->conn = new PDO("mysql:host=" . $this->DBhost  .";port=3306; dbname=" . $this->DBname, $this->DBuser, $this->DBpwd);
              $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
           }
           catch(PDOException $e){
              $conn = $e->getMessage();
           }

           return $conn;
       }

       /**
       * @param $sql
       * @return PDOStatement
       */
       public function runQuery($sql){
          $stmt = $this->conn->prepare($sql);
          return $stmt;
       }

       /**
       * @return string
       */
       public function lastID(){
         $stmt = $this->conn->lastInsertId();
         return $stmt;
       }

      public function insertC2B($TransID, $MSISDN, $AccNo, $KYCInfo, $Amount){
         $result = null;
         try{
               $sql = "INSERT INTO c2b(TransID,MSISDN,BillRefNumber,KYCInfo,Amount) VALUES(':TransID',':MSISDN',':AccountNo',':KYCInfo',':TransAmount')";
               $stmt = $this->runQuery($sql);
               $stmt->bindParam(':TransID', $TransID);
               $stmt->bindParam(':MSISDN', $MSISDN);
               $stmt->bindParam(':AccountNo', $AccountNo);
               $stmt->bindParam(':KYCInfo', $KYCInfo);
               $stmt->bindParam(':TransAmount', $Amount);
               $stmt->execute();

               $result = $this->lastID();
            } catch (PDOException $e){
               $result = $e->getMessage();
            }
            return $result;
         }
      }

【讨论】:

    【解决方案2】:

    这对我有用。我用preg_replace

    <?php
    header('Content-type: text/xml');
    $request= <<<XML
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:c2b="http://cps.huawei.com/cpsinterface/c2bpayment">
    <soapenv:Header/>
    <soapenv:Body>
      <c2b:C2BPaymentValidationRequest>
         <TransactionType>PayBill</TransactionType>
         <TransID>1234560000007031</TransID>
         <TransTime>20140227082020</TransTime>
         <TransAmount>123.00</TransAmount>
         <BusinessShortCode>12345</BusinessShortCode>
    <BillRefNumber></BillRefNumber>
         <InvoiceNumber></InvoiceNumber>
    <MSISDN>254722703614</MSISDN>
         <KYCInfo>
      <KYCName>[Personal Details][First Name]</KYCName>
      <KYCValue>Hoiyor</KYCValue>
    </KYCInfo>
    <KYCInfo>
      <KYCName>[Personal Details][Middle Name]</KYCName>
      <KYCValue>G</KYCValue>
    </KYCInfo>
    <KYCInfo>
      <KYCName>[Personal Details][Last Name]</KYCName>
      <KYCValue>Chen</KYCValue>
    </KYCInfo>
      </c2b:C2BPaymentValidationRequest>
    </soapenv:Body>
    </soapenv:Envelope>
    XML;
    
    $xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $request);
    $xml = simplexml_load_string($xml);
    $json = json_encode($xml);
    $responseArray = json_decode($json,true);
    
    //VALUES
    $transaction_type = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["TransType"]);
    $TransID = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["TransID"]);
    $TransTime = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["TransTime"]);
    $TransAmount = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["TransAmount"]);
    $BusinessShortCode = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["BusinessShortCode"]);
    $MSISDN = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["MSISDN"]);
    $BusinessShortCode = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["BusinessShortCode"]);
    $BillRefNumber = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["BillRefNumber"]);
    $InvoiceNumber = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["InvoiceNumber"]);
    $OrgAccountBalance = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["OrgAccountBalance"]);
    $ThirdPartyTransID = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["ThirdPartyTransID"]);
    
    $KYCInfo = ($responseArray["soapenvBody"]["ns1C2BPaymentConfirmationRequest"]["KYCInfo"]);
    $title = $KYCInfo[0]["KYCName"];
    $title = $KYCInfo[1]["KYCName"];
    $title = $KYCInfo[2]["KYCName"];
    $name = $KYCInfo[0]["KYCValue"]." ".$KYCInfo[1]["KYCValue"]." ".$KYCInfo[2]["KYCValue"];
    
    //LOCAL MYSQLI SERVER
    $server = 'localhost';
    $user = 'user';
    $pass = 'pass';
    $db  = 'db'; 
    
    // Create connection
    $conn = new mysqli($server, $user, $pass, $db);
    // Check connection
    //if ($conn->connect_error) {  die("Connection failed: " . $conn->connect_error); } 
    $query = "INSERT INTO table(B,C,D,E,F,G,H,J) VALUES('$TransID','$MSISDN','$BillRefNumber','$name','$TransAmount','$InvoiceNumber','$ThirdPartyTransID','$OrgAccountBalance')";
    if (mysqli_query($conn,$query) === TRUE)
            {  
            $string = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://cps.huawei.com/cpsinterface/ns1payment">
               <soapenv:Header/>
               <soapenv:Body>
                  <ns1:C2BPaymentConfirmationResult>C2B Payment Transaction '.$TransID.' result received.</ns1:C2BPaymentConfirmationResult>
               </soapenv:Body>
            </soapenv:Envelope>
            ';
    
            $xml = new SimpleXMLElement($string);
            echo $xml->asXML();
            mysqli_close($conn);
            } 
            else 
            {
              $string = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://cps.huawei.com/cpsinterface/ns1payment">
               <soapenv:Header/>
               <soapenv:Body>
                  <ns1:C2BPaymentConfirmationResult>C2B Payment Transaction '.$TransID.' result not received.</ns1:C2BPaymentConfirmationResult>
               </soapenv:Body>
            </soapenv:Envelope>';
    
            $xml = new SimpleXMLElement($string);
            echo $xml->asXML();
            mysqli_close($conn);
            } 
    ?> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      • 2014-05-21
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多