【问题标题】:Send XML with php via post通过 post 使用 php 发送 XML
【发布时间】:2013-07-21 16:41:30
【问题描述】:

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

所以如果我有以下

$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>";

(我对其进行了编辑以包含我的实际 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);

【问题讨论】:

  • 通过 post 发送此 XML 的 php 代码是什么样的?
  • 我编辑了它以添加它
  • 好的...那么什么部分不起作用?您是否收到任何特定的错误消息?
  • 没有错误...只是白屏,没有输出。我在 codeigniter 中执行此操作,除非出现灾难性错误,否则我至少应该在没有任何输出的情况下获取 html,因此出现灾难性错误
  • 所以我假设你说我的卷曲是 100% 正确的?

标签: php xml soap


【解决方案1】:

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

看看http://www.php.net/manual/en/soapclient.soapcall.php#example-5266如何使用SOAP webservice。这并不难理解。

这里有一些代码可以用来分析网络服务。然后将类型映射到类并发送和接收 php 对象。你可以找一些工具来自动生成类(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
}

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

<?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();
}

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

这是捕获的通信:

请求

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>

回应

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>

【讨论】:

  • 我已经编辑了我的帖子以包含我的实际 xml.... 共识似乎是我的 curl 是正确的但我的 xml 是错误的?
  • 也许你有共识,但不是更好的方法。 :-)
  • 我希望我能给它 50 票,因为它是一个了不起的答案
【解决方案2】:

首先,如果您的代码是这样编写的,我怀疑这是因为引号引起的... 您应该在 xml 周围使用双引号:

$my_xml = "<?xml version='1.0' standalone='yes'?>
           <user> 
               <Name>xmltest@freightquote.com</Name> 
               <Password>XML</Password> 
           </user>";

另外,您可以使用 poster,一个 firefox 插件(chrome 上可能有等效插件)来帮助您处理您的请求,尤其是在您使用 WebServices 时。这样,您将能够查看错误是服务器端的还是客户端的。

这应该可以帮助您调试。

【讨论】:

    【解决方案3】:

    我使用这个命令行脚本来测试 SOAP 调用:

    #!/usr/bin/php
    <?php
    //file client-test.php
    $xml_data = file_get_contents('php://stdin');
    
    $ch = curl_init('http://example.com/server/');
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('SOAPAction', 'MySoapAction'));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    
    print_r($output);
    

    这样的用法(在命令行中): $ client-test.php &lt; yourSoapEnveloppe.xml

    在此示例中,yourSoapEnveloppe.xml 文件是您的 $xml 变量的内容。

    【讨论】:

      【解决方案4】:

      您可以使用stream_context_createfile_get_contents 在post 中发送xml。

      $xml = "<your_xml_string>";
      $send_context = stream_context_create(array(
          'http' => array(
          'method' => 'POST',
          'header' => 'Content-Type: application/xml',
          'content' => $xml
          )
      ));
      
      print file_get_contents($url, false, $send_context);
      

      【讨论】:

        猜你喜欢
        • 2010-12-12
        • 1970-01-01
        • 2014-03-12
        • 1970-01-01
        • 2010-09-19
        • 2011-02-18
        • 1970-01-01
        • 2011-02-03
        • 1970-01-01
        相关资源
        最近更新 更多