zoukankan      html  css  js  c++  java
  • php通过curl发送XML数据,并获取XML数据

    php编程中经常会用到用xml格式传送数据,如调用微信等第三方接口经常用到,这里演示下php以curl形式发送xml,并通过服务器接收

    一、发送xml数据 —— postXml.php

    <?php
    

    // 首先检测是否支持curl
    if (!extension_loaded("curl")) {
    trigger_error("对不起,请开启curl功能模块!", E_USER_ERROR);
    }

    // 构造xml数据
    $xmlData = "
    <xml>
    <AppId>wxf8b4f85f3a794e77</AppId>
    <ErrorType>1001</ErrorType>
    <Description>错误描述</Description>
    <AlarmContent>transaction_id=33534453534</AlarmContent>
    <TimeStamp>1393860740</TimeStamp>
    <AppSignature>f8164781a303f4d5a944a2dfc68411a8c7e4fbea</AppSignature>
    <SignMethod>sha1</SignMethod>
    </xml>"
    ;

    $url = 'http://web.whm.com/getXml.php'; //接收xml数据的文件
    $ch = curl_init(); // 初始一个curl会话
    $timeout = 30; // php运行超时时间,单位秒
    curl_setopt($ch, CURLOPT_URL, $url); // 设置url
    curl_setopt($ch, CURLOPT_POST, 1); // post 请求
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:text/xml; charset=utf-8")); // 一定要定义content-type为xml,要不然默认是text/html!
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);//post提交的数据包
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); // PHP脚本在成功连接服务器前等待多久,单位秒
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $result = curl_exec($ch); // 抓取URL并把它传递给浏览器
    // 是否报错
    if(curl_errno($ch))
    {
    print curl_error($ch);
    }
    curl_close($ch); // //关闭cURL资源,并且释放系统资源

    echo $result;

    php通过curl发送XML数据,并获取XML数据

    二、接收xml数据——getXml.php

    <?php
    

    //接收传送的数据
    $xml = file_get_contents("php://input");

    //将xml数据写入文本文件"whm.txt"中
    $handle =fopen('whm.txt','w');

    fwrite($handle,$xml);

    php通过curl发送XML数据,并获取XML数据

    三、注意事项

    1. 构造xml时一定要注意格式正确,不能有空格等
    2. 一定要定义content-type为xml,要不然默认是text/html

    转载请标明原文链接: https://www.jianshu.com/p/7b86546f5300
    更多精彩请访问个人博客:https://www.whmblog.cn/

          </div>
  • 相关阅读:
    Vue.js 监听属性
    class 属性绑定
    《规划极限编程》阅读笔记03
    原型模式——C++实现
    原型模式——Java实现
    建造者模式——C++实现
    建造者模式——java实现
    抽象工厂模式——C++实现
    抽象工厂模式——java实现
    软件工程 开发模型
  • 原文地址:https://www.cnblogs.com/showcase/p/11264537.html
Copyright © 2011-2022 走看看