Php 使用str_ireplace函数清理xml数据

Php 使用str_ireplace函数清理xml数据,php,mysql,xml-parsing,Php,Mysql,Xml Parsing,当我运行脚本时,它在数据库中存储空格。我哪里做错了。下面是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/

当我运行脚本时,它在数据库中存储空格。我哪里做错了。下面是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 />";       
}   
}                                                                                                                  

?>
$cur)
{
//价值观
$AccountNo=$cur->BillRefNumber;
$TransAmount=$cur->TransAmount;
$TransID=$cur->TransID;
$KYCInfo=$cur->KYCInfo;
$MSISDN=$cur->MSISDN;
//保存到数据库
$link=mysql\u connect($server,$user,$pass)或die(mysql\u error());
$conn=mysql\u select\u db($db)或die(mysql\u error($link));
$query=“插入c2b(TransID、MSISDN、BillRefNumber、KYCInfo、Amount)值(“$TransID”、“$MSISDN”、“$AccountNo”、“$KYCInfo”、“$TransAmount”)”;
if(!mysql_query($query))
{
die('Error:'.mysql_Error());
}
其他的
{
echo“已成功添加新记录!

”; } } ?>

我怀疑错误在于使用str_ireplace函数解析xml数据。我已经阅读了PHP文档,似乎我已经按照书中的内容完成了所有工作。

我建议您在以下几点使用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;
         }
      }

这是为我工作。我使用了
preg\u 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);
        } 
?> 
connect_error);}
$query=“在表(B、C、D、E、F、G、H、J)中插入值(“$TransID”、“$MSISDN”、“$BillRefNumber”、“$name”、“$TransAmount”、“$InvoiceNumber”、“$ThirdPartyTransID”、“$OrgAccountBalance”);
if(mysqli_查询($conn,$query)==TRUE)
{  
$string='1
收到C2B支付交易记录“$TransID.”结果。
';
$xml=新的simplexmlement($string);
echo$xml->asXML();
mysqli_close($conn);
} 
其他的
{
$string='1
未收到C2B支付交易记录“$TransID.”结果。
';
$xml=新的simplexmlement($string);
echo$xml->asXML();
mysqli_close($conn);
} 
?> 

出于许多原因,您不应该再使用mysql_*函数了。如果您从教程中复制了这段代码,那么寻找另一段代码可能是个好主意。您是否考虑过查看生成的SQL代码?我想我之前的评论不清楚。添加
var\u转储($query)紧跟在
$query=…
行之后,按Ctrl+U查看原始输出。@阿尔瓦罗冈萨雷斯这是我得到的响应
string(82)“插入c2b(TransID,MSISDN,BillRefNumber,KYCInfo,Amount)值(“”,“”,“”,“”,“”,“”)
Voilá!您刚刚丢弃了调查中的一半代码;-)