将PHP变量插入CURL XML post

时间:2016-01-25 20:12:22

标签: php xml curl

我有点卡在这里,如果有人能指出我正确的方向,我会非常感激:)

我从表单中发布“unauth”值并检索它。我想要做的是将它插入到我作为变量发布的XML中。该变量需要插入macAddress字段中。这就是我的想法

macAddress =“ $ unauth ”(第8行)

<?php 
  session_start();
$unauth = $_POST['unauth'];
$xml_data = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TipsApiRequest xmlns="http://www.avendasys.com/tipsapiDefs/1.0">
<TipsHeader version="3.0"/>
<Endpoints>
<Endpoint status="Known" macAddress="$unauth">
<EndpointTags tagName="unauthorized" tagValue="true"/>
</Endpoint>
</Endpoints>
</TipsApiRequest>';
$c = curl_init();
curl_setopt($c, CURLOPT_URL, "https://x.x.x.x/tipsapi/config/write/Endpoint");
curl_setopt($c, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($c, CURLOPT_USERPWD, 'username:password');
curl_setopt($c, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($c, CURLOPT_HEADER, false);

$output2 = curl_exec($c);

if($output2 === false)
{
trigger_error('Erreur curl : '.curl_error($c),E_USER_WARNING);
}
else
{`enter code here`
var_dump($output2);
var_dump($_POST);
}
curl_close($c);
?>

这是我得到的XML响应

'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><TipsApiResponse xmlns="http://www.avendasys.com/tipsapiDefs/1.0"><TipsHeader exportTime="Mon Jan 25 20:10:18 GMT 2016" version="6.5"/><StatusCode>Success</StatusCode><TipsApiError><ErrorCode>InvalidXml</ErrorCode><Message>Endpoint MAC Address "&amp;#x24;unauth" is invalid</Message></TipsApiError></TipsApiResponse>

非常感谢!

1 个答案:

答案 0 :(得分:0)

您在XML字符串构造中使用简单引号'。在简单引号内,不解释变量。您必须将XML字符串封装在双引号"中,或者将变量连接到字符串中。

<?php
$s = 'a string';
echo '$s'; // Show $s
echo "$s"; // Show a string

连接字符串的示例:

$unauth = 'attribute value';
$xml_data = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TipsApiRequest xmlns="http://www.avendasys.com/tipsapiDefs/1.0">
    <TipsHeader version="3.0"/>
    <Endpoints>
        <Endpoint status="Known" macAddress="'.$unauth.'">
            <EndpointTags tagName="unauthorized" tagValue="true"/>
        </Endpoint>
    </Endpoints>
</TipsApiRequest>';

您还可以使用HEREDOC字符串构造来解释其中的变量:

$unauth = 'attribute value';
$xml_data = <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TipsApiRequest xmlns="http://www.avendasys.com/tipsapiDefs/1.0">
    <TipsHeader version="3.0"/>
    <Endpoints>
        <Endpoint status="Known" macAddress="$unauth">
            <EndpointTags tagName="unauthorized" tagValue="true"/>
        </Endpoint>
    </Endpoints>
</TipsApiRequest>
XML;

此外,您必须使用PHP filters函数验证POST数据,以避免在XML请求中注入代码。