curl发送xml , xml和数组互转

时间:2021-10-04 15:17:16
public function postXml($url, array $data)
{
// pack xml
$xml = $this->arrayToXml($data); // curl post
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
$response = curl_exec($ch);
if (!$response) {
throw new Exception('CURL Error: ' . curl_errno($ch));
}
curl_close($ch); // unpack xml
return $this->xmlToArray($response);
} public function arrayToXml(array $data)
{
$xml = "<xml>";
foreach ($data as $k => $v) {
if (is_numeric($v)) {
$xml .= "<{$k}>{$v}</{$k}>";
} else {
$xml .= "<{$k}><![CDATA[{$v}]]></{$k}>";
}
}
$xml .= "</xml>";
return $xml;
} public function xmlToArray($xml)
{
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}