2017-02-21 7 views
0

Когда я запускал скрипт, он хранит пробелы в базе данных. Где я иду не так. Ниже приведен скрипт:Очистка данных xml с использованием функции str_ireplace

<?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 />";  
} 
}                             

?> 

Я подозреваю, что ошибка в анализе данных XML с помощью функции str_ireplace. Я просмотрел документацию по PHP, и кажется, что я сделал все по книге.

+1

По многим причинам вы больше не должны использовать функции mysql_ *. Если вы скопировали этот код из учебника, возможно, это хорошая идея, чтобы искать другой. –

+0

Рассматривали ли вы просмотр ** сгенерированного ** кода SQL? –

+0

Я предполагаю, что мой предыдущий комментарий был неясным. Добавьте 'var_dump ($ query);' прямо после строки '$ query = ...' и нажмите Ctrl + U, чтобы увидеть исходный вывод. –

ответ

0

Я предлагаю вам использовать 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; 
     } 
     } 
0

Это работало для меня. Я использовал 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); 
     } 
?> 
Смежные вопросы