2017-02-16 67 views
1

我想從php中發送數據作爲xml post請求,但是出現錯誤。如何在PHP中使用http post發送表單數據作爲PHP

//taking form data into custom variables 
$customer_state = $_POST['customer_state']; 
$lastname = $_POST['lastname']; 
$firstname = $_POST['firstname']; 
// creating xml from form data 
$xml = ' <?xml version="1.0" encoding="UTF-8"?> 
<crcloud> 
       <lead> 
       <type>trim($customer_state);</type> 
       <firstname>trim($firstname);</firstname> 
       <lastname>trim($lastname);</lastname> 
       </lead> 
      </crcloud>'; 
//trying to send the xml as a post request 
$url was pre defined here 

    $stream_options = array(
'http' => array(
'method' => 'POST', 
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n", 
'content' => $xml)); 

$context = stream_context_create($stream_options); 
$response = file_get_contents($url, null, $context); 
echo $response; 

我得到的迴應是「不允許的關鍵字符」。

回答

0

您不能在單引號字符串中插入變量,也不能在字符串上下文中執行像trim這樣的函數。另外,您的Content-type對於發送XML不正確。

嘗試這種方式

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><crcloud/>'); 
$lead = $xml->addChild('lead'); 
$lead->addChild('type', trim($customer_state)); 
$lead->addChild('firstname', trim($firstname)); 
$lead->addChild('lastname', trim($lastname)); 

'header' => "Content-type: text/xml\r\n", 
'content' => $xml->asXML()