0

我无法将数组转换为 xml,然后将其作为 xml 帖子发布到第三方 URL。

我相信我很接近,但我缺少一些东西让它起作用。我正在使用 wordpress 和重力形式(我认为这不重要)

这是我到目前为止所拥有的。

function post_to_third_party($entry, $form) {

  $post_url = 'https://xxxx.com/home/BorrowerImport.do?CampaignID=xxx';
  $body = array( 'firstname' => $entry['8.3'],      
    'lastname' => $entry['8.6'],
    'dayphone' => $entry['12'],
    'email' => $entry['11']    
  );

  $xml = new SimpleXMLElement('<application/>');
  $body = array_flip($body);
  array_walk($body, array ($xml, 'addChild'));
  print $xml->asXML();

  $ch = curl_init($url);
  //curl_setopt($ch, CURLOPT_MUTE, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $post_url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  $output = curl_exec($ch);
  echo $output;

  curl_close($ch); 
} 

我还尝试了以下代码,这似乎有效,但 var_dump 看起来像 string(201) " $firstname $lastname $dayphone $email " ok

我不知道如何使用从 $body 数组收集的数据填充 xml 标记

这是我用于此结果的代码

add_action('gform_after_submission', 'post_to_third_party', 10, 2);
function post_to_third_party($entry, $form) {

$post_url = 'https://xxxx.com/home/BorrowerImport.do?CampaignID=xxx';
$body = array(
    'firstname' =>     $entry['8.3'],      
    'lastname' =>     $entry['8.6'],
    'dayphone' =>   $entry['12'],
    'email' =>  $entry['11']    
    );
$xml = '

    <?xml version="1.0" encoding="UTF-8"?>
    <application>
    <firstname>$firstname</firstname>
    <lastname>$lastname</lastname>
    <dayphone>$dayphone</dayphone>
    <email>$email</email>
    </application>';
var_dump($xml);

$ch = curl_init($url);
    //curl_setopt($ch, CURLOPT_MUTE, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $post_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $output = curl_exec($ch);
    echo $output;

    curl_close($ch);

}
4

1 回答 1

0

好的,问题来了:

在转换为 XML 之前用于构建数组的方法是意外删除了一些数据。

你从这样的事情开始:

$body = array(
    "firstname" => "Test",
    "lastname" => "Test",
    "dayphone" => "(801)735-2222",
    "email" => "test@gmail.com",
);

然后你打电话array_flip给你:

$body = array(
    "Test" => "firstname",
    "Test" => "lastname",
    "(801)735-2222" => "dayphone",
    "test@gmail.com" => "email",
);

现在,您的数组中有两个“测试”键。PHP 保留最后一个并丢弃第一个。因此,您的 XML 文档现在缺少一个必需的键:“名字”。

解决方案是以老式的方式构建您的 XML 文档,并远离花哨的东西,例如array_flip

foreach($body as $k=$v)
    $xml->addChild($k, $v);
于 2014-04-07T21:53:46.577 回答