如何使用php中的http post将表单数据作为xml发送

时间:2017-02-16 22:48:12

标签: php xml http post

我想从我的for发送数据作为php中的xml帖子请求,但是我收到了错误。

//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;

我得到的回答是“不允许使用关键字符。”

1 个答案:

答案 0 :(得分: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()