通过 post 用 php 发送 XML [英] Send XML with php via post

查看:33
本文介绍了通过 post 用 php 发送 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在 SO 上有许多类似的问题,但我已经尝试解决所有解决方案,但似乎无法使其发挥作用.我正在尝试将 xml 直接发布到 Web 服务并获得响应.从技术上讲,我正在尝试连接到 Freightquote.com,您可以在 的右上角找到相关文档这个页面在文档下.我之所以提到这一点,是因为我在他们的 xml 中经常看到术语 SOAP,它可能会有所作为.无论如何,我想要的是将 xml 发送到某个 url 并获得响应的能力.

所以如果我有以下内容

$xml = "<肥皂:身体><GetRatingEngineQuote xmlns='http://tempuri.org/'><请求><CustomerId>0</CustomerId><!-- Freightquote 提供的客户标识符 --><QuoteType>B2B</QuoteType><!-- B2B/eBay/Freightview --><ServiceType>LTL</ServiceType><!-- LTL/Truckload/Groupage/Haulage/Al --><报价发货><IsBlind>false</IsBlind><取件日期>2010-09-13T00:00:00</取件日期><SortAndSegregate>false</SortAndSegregate><发货地点><位置><LocationType>来源</LocationType><RequiresArrivalNotification>false</RequiresArrivalNotification><HasDeliveryAppointment>false</HasDeliveryAppointment><IsLimitedAccess>false</IsLimitedAccess><HasLoadingDock>false</HasLoadingDock><IsConstructionSite>false</IsConstructionSite><RequiresInsideDelivery>false</RequiresInsideDelivery><IsTradeShow>false</IsTradeShow><IsResidential>false</IsResidential><RequiresLiftgate>false</RequiresLiftgate><位置地址><邮政编码>30303</邮政编码><CountryCode>美国</CountryCode></位置地址><附加服务/></位置><位置><LocationType>目的地</LocationType><RequiresArrivalNotification>false</RequiresArrivalNotification><HasDeliveryAppointment>false</HasDeliveryAppointment><IsLimitedAccess>false</IsLimitedAccess><HasLoadingDock>false</HasLoadingDock><IsConstructionSite>false</IsConstructionSite><RequiresInsideDelivery>false</RequiresInsideDelivery><IsTradeShow>false</IsTradeShow><IsResidential>false</IsResidential><RequiresLiftgate>false</RequiresLiftgate><位置地址><邮政编码>60606</邮政编码><CountryCode>美国</CountryCode></位置地址><附加服务/></位置></ShipmentLocations><出货产品><产品><班级>55</班级><重量>1200</重量><长度>0</长度><宽度>0</宽度><高度>0</高度><ProductDescription>书籍</ProductDescription><PackageType>Pallets_48x48</PackageType><IsStackable>false</IsStackable><DeclaredValue>0</DeclaredValue><CommodityType>GeneralMerchandise</CommodityType><ContentType>NewCommercialGoods</ContentType><IsHazardousMaterial>false</IsHazardousMaterial><PieceCount>5</PieceCount><ItemNumber>0</ItemNumber></产品></发货产品><发货联系人/></QuoteShipment></请求><用户><姓名>someone@something.com</姓名><密码>密码</密码></用户></GetRatingEngineQuote></soap:Body></soap:Envelope>";

(我编辑了这个以包含我的实际 xml,因为它可能会提供一些视角

我想将它发送到 http://www.someexample.com 并得到回复.另外,我需要编码吗?我已经用 android 来回发送了很多 xml,而且从来没有这样做过,但这可能是我的问题的一部分.

我尝试发送的信息目前看起来像这样

$xml_post_string = 'XML='.urlencode($xml->asXML());$ch = curl_init();curl_setopt($ch, CURLOPT_URL, 'https://b2b.Freightquote.com/WebService/QuoteService.asmx');curl_setopt($ch, CURLOPT_POST, TRUE);curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);$response = curl_exec($ch);curl_close($ch);

解决方案

如果您正在使用 SOAP 服务,我强烈建议您学习一次基础知识,然后一次又一次地使用这个伟大的工具.您可以使用许多功能,否则您将重新发明轮子并努力生成 xml 文件、解析 xml 文件、错误等.使用准备好的工具,您的生活会更轻松,您的代码会更好(错误更少).

查看http://www.php.net/manual/en/soapclient.soapcall.php#example-5266 如何使用 SOAP 网络服务.不难理解.

这里是一些如何分析网络服务的代码.然后将类型映射到类,然后发送和接收 php 对象.您可以寻找一些工具来自动生成类(http://www.urdalen.no/wsdl2php/manual.php).

__getFunctions();var_dump($functions);//读取一些请求对象$response = $client->__getTypes();var_dump($response);}捕获 (SoapFault $e){//做一些服务级别错误的事情}捕获(异常 $e){//做一些应用级错误的事情}

如果你会使用 wsdl2php 生成工具,一切都非常简单:

BOLNumber = 67635735;$request = new GetTrackingInformation();$request->request = $tracking;//发送请求$response = $client->GetTrackingInformation($request);var_dump($response);}捕获 (SoapFault $e){//做一些服务级别错误的事情回声肥皂错误".$e->getMessage();}捕获(异常 $e){//做一些应用级错误的事情回声'错误'.$e->getMessage();}

QuoteService.php 生成的 php 代码,您可以在这里看到:http://pastie.org/8165331

这是捕获的通信:

请求

POST/WebService/QuoteService.asmx HTTP/1.1主持人:b2b.freightquote.com连接:保持活动用户代理:PHP-SOAP/5.4.17内容类型:文本/xml;字符集=utf-8SOAPAction:http://tempuri.org/GetTrackingInformation"内容长度:324<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/"><SOAP-ENV:Body><ns1:GetTrackingInformation><ns1:request><ns1:BOLNumber>67635735</ns1:BOLNumber></ns1:request></ns1:GetTrackingInformation></SOAP-ENV:Body></SOAP-ENV:Envelope>

回复

HTTP/1.1 200 OK日期:2013 年 7 月 22 日星期一 21:46:06 GMT服务器:Microsoft-IIS/6.0X-Powered-By: ASP.NETX-AspNet 版本:2.0.50727缓存控制:私有,最大年龄=0内容类型:文本/xml;字符集=utf-8内容长度:660设置-Cookie:BIGipServerb2b_freightquote_com=570501130.20480.0000;路径=/<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd=http://www.w3.org/2001/XMLSchema"><肥皂:身体><GetTrackingInformationResponse xmlns="http://tempuri.org/"><获取跟踪信息结果><BOLNumber>0</BOLNumber><预计交货期>0001-01-01T00:00:00</预计交货期><跟踪日志/><验证错误><B2BError><ErrorType>验证</ErrorType><ErrorMessage>无法找到带有 BOL 67635735 的货件.</ErrorMessage></B2BError></ValidationErrors></GetTrackingInformationResult></GetTrackingInformationResponse></soap:Body></soap:Envelope>

I know there are any number of similar questions to this on SO, but I've tried messing around with all the solutions and haven't seemed to be able to make it work. I am trying to post xml directly to a web service and get a response back. Technically I am trying to connect to freightquote.com, the documentation for which you can find in the upper right hand corner of this page under documentation. I only mention that because I see the term SOAP a lot in their xml and it might make a difference. Anyway what I want is the ability to send xml to some url and get a response back.

So if I had the following

$xml = "<?xml version='1.0' encoding='utf-8'?>
            <soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' 
            xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
            xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
            <soap:Body>
              <GetRatingEngineQuote xmlns='http://tempuri.org/'>
                <request>
                  <CustomerId>0</CustomerId> <!-- Identifier for customer provided by Freightquote -->
                  <QuoteType>B2B</QuoteType> <!-- B2B / eBay /Freightview -->
                  <ServiceType>LTL</ServiceType> <!--  LTL / Truckload / Groupage / Haulage / Al  -->
                  <QuoteShipment>
                    <IsBlind>false</IsBlind>
                    <PickupDate>2010-09-13T00:00:00</PickupDate>
                    <SortAndSegregate>false</SortAndSegregate>
                    <ShipmentLocations>
                      <Location>
                        <LocationType>Origin</LocationType>
                        <RequiresArrivalNotification>false</RequiresArrivalNotification>
                        <HasDeliveryAppointment>false</HasDeliveryAppointment>
                        <IsLimitedAccess>false</IsLimitedAccess>
                        <HasLoadingDock>false</HasLoadingDock>
                        <IsConstructionSite>false</IsConstructionSite>
                        <RequiresInsideDelivery>false</RequiresInsideDelivery>
                        <IsTradeShow>false</IsTradeShow>
                        <IsResidential>false</IsResidential>
                        <RequiresLiftgate>false</RequiresLiftgate>
                        <LocationAddress>
                          <PostalCode>30303</PostalCode>
                          <CountryCode>US</CountryCode>
                        </LocationAddress>
                        <AdditionalServices />
                      </Location>
                      <Location>
                        <LocationType>Destination</LocationType>
                        <RequiresArrivalNotification>false</RequiresArrivalNotification>
                        <HasDeliveryAppointment>false</HasDeliveryAppointment>
                        <IsLimitedAccess>false</IsLimitedAccess>
                        <HasLoadingDock>false</HasLoadingDock>
                        <IsConstructionSite>false</IsConstructionSite>
                        <RequiresInsideDelivery>false</RequiresInsideDelivery>
                        <IsTradeShow>false</IsTradeShow>
                        <IsResidential>false</IsResidential>
                        <RequiresLiftgate>false</RequiresLiftgate>
                        <LocationAddress>
                          <PostalCode>60606</PostalCode>
                          <CountryCode>US</CountryCode>
                        </LocationAddress>
                        <AdditionalServices />
                      </Location>
                    </ShipmentLocations>
                    <ShipmentProducts>
                      <Product>
                        <Class>55</Class>
                        <Weight>1200</Weight>
                        <Length>0</Length>
                        <Width>0</Width>
                        <Height>0</Height>
                        <ProductDescription>Books</ProductDescription>
                        <PackageType>Pallets_48x48</PackageType>
                        <IsStackable>false</IsStackable>
                        <DeclaredValue>0</DeclaredValue>
                        <CommodityType>GeneralMerchandise</CommodityType>
                        <ContentType>NewCommercialGoods</ContentType>
                        <IsHazardousMaterial>false</IsHazardousMaterial>
                        <PieceCount>5</PieceCount>
                        <ItemNumber>0</ItemNumber>
                      </Product>
                    </ShipmentProducts>
                    <ShipmentContacts />
                  </QuoteShipment>
                </request>
                <user>
                  <Name>someone@something.com</Name>
                  <Password>password</Password>
                </user>
              </GetRatingEngineQuote>
            </soap:Body>
            </soap:Envelope>";

(I edited this to contain my actual xml since it may lend some perspective

I'd want to send it to http://www.someexample.com and get a response. Also, do I need to encode it? I've done a lot of sending xml back and forth with android, and never had to but that might be part of my problem.

My attempt to send the information currently looks like this

$xml_post_string = 'XML='.urlencode($xml->asXML());  
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, 'https://b2b.Freightquote.com/WebService/QuoteService.asmx');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);
curl_close($ch);

解决方案

If you are walking around SOAP services, I strongly recommend you to learn basics once, and then use this great tool again and again. There are many features you can just use, or you will be reinventing the wheel and struggling with generating xml files, parsing xml files, faults etc. Use prepared tools and your life will be easier and your code better (less bugs).

Look at http://www.php.net/manual/en/soapclient.soapcall.php#example-5266 how to consume SOAP webservice. It is not so hard to understand.

Here is some code how you can analyze webserivce. Then map types to classes and just send and receive php objects. You can look for some tool to generate classes automatically (http://www.urdalen.no/wsdl2php/manual.php).

<?php
try
{
    $client = new SoapClient('http://b2b.freightquote.com/WebService/QuoteService.asmx?WSDL');

    // read function list
    $funcstions = $client->__getFunctions();
    var_dump($funcstions);

    // read some request obejct
    $response = $client->__getTypes();
    var_dump($response);
}
catch (SoapFault $e)
{
    // do some service level error stuff
}
catch (Exception $e)
{
    // do some application level error stuff
}

If you will use wsdl2php generating tool, everything is very easy:

<?php

require_once('./QuoteService.php');

try
{
    $client = new QuoteService();

    // create request
    $tracking = new TrackingRequest();
    $tracking->BOLNumber = 67635735;

    $request = new GetTrackingInformation();
    $request->request = $tracking;

    // send request
    $response = $client->GetTrackingInformation($request);
    var_dump($response);
}
catch (SoapFault $e)
{
    // do some service level error stuff
    echo 'Soap fault ' . $e->getMessage();
}
catch (Exception $e)
{
    // do some application level error stuff
    echo 'Error ' . $e->getMessage();
}

Generated php code for QuoteService.php you can see here: http://pastie.org/8165331

This is captured communication:

Request

POST /WebService/QuoteService.asmx HTTP/1.1
Host: b2b.freightquote.com
Connection: Keep-Alive
User-Agent: PHP-SOAP/5.4.17
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://tempuri.org/GetTrackingInformation"
Content-Length: 324

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/">
    <SOAP-ENV:Body>
        <ns1:GetTrackingInformation>
            <ns1:request>
                <ns1:BOLNumber>67635735</ns1:BOLNumber>
            </ns1:request>
        </ns1:GetTrackingInformation>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Response

HTTP/1.1 200 OK
Date: Mon, 22 Jul 2013 21:46:06 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Content-Length: 660
Set-Cookie: BIGipServerb2b_freightquote_com=570501130.20480.0000; path=/

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <GetTrackingInformationResponse xmlns="http://tempuri.org/">
            <GetTrackingInformationResult>
                <BOLNumber>0</BOLNumber>
                <EstimatedDelivery>0001-01-01T00:00:00</EstimatedDelivery>
                <TrackingLogs />
                <ValidationErrors>
                    <B2BError>
                        <ErrorType>Validation</ErrorType>
                        <ErrorMessage>Unable to find shipment with BOL 67635735.</ErrorMessage>
                    </B2BError>
                </ValidationErrors>
            </GetTrackingInformationResult>
        </GetTrackingInformationResponse>
    </soap:Body>
</soap:Envelope>

这篇关于通过 post 用 php 发送 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆