使用PHP创建SOAP请求 - 如何向XML标记添加属性?

时间:2009-09-10 06:17:25

标签: php xml soap

我正在尝试在SOAP调用中生成以下XML:

<CResponse>
    <ID>int</ID>
    <Response Action="Apply">
        <Question ID="$someint">
            <Responses>
                <Response ID="$someotherint" />
                <Response ID="$yetanotherint" />
            </Responses>
        </Question>
    </Response>
</CResponse>

我可以很好地创建大部分调用 - 我终于认识到嵌套数组是我的朋友 - 但我不知道如何将这些ID="$int"Action="Apply"属性添加到各种标签。我相信这很容易,但我无法理解。

TIA。

3 个答案:

答案 0 :(得分:13)

您应该能够使用以下语法添加属性:

array("foo" => array("_" => "cheese", "bar"=>"moo"));

这应该产生以下XML

<foo bar="moo">cheese</foo>

答案 1 :(得分:1)

我不知道JJ建议的(有点奇怪)语法(并且根据你对问题的重新发布,它似乎不起作用),但是你应该能够根据需要调整你的请求xml通过使用SoapVar编码的XSD_ANYXML类或多或少“手动”来构建它。

有关如何执行此操作的示例,请参阅this user comment to the SoapVar Constructor documentation

如果您需要构建的XML变得更复杂,请考虑使用SimpleXML或DOMDocument来组装它而不是直接编写它。

(对我来说似乎很奇怪,应该没有更简单的方法来做到这一点,但到目前为止我还没有找到一个。)


编辑:刚刚在this question asking for a simpler way to do it中找到了另一个使用XSD_ANYXML编码的示例。不幸的是到目前为止还没有人想出更简单的方法:/

答案 2 :(得分:1)

我遇到了与属性相同的问题,最后我在本文中使用了XMLWriter:http://eosrei.net/articles/2012/01/php-soap-xml-attributes-namespaces-xmlwriter

构建请愿书:

$prefix = 'ns1';

$xml = new \XMLWriter();
$xml->openMemory();

$xml->startElementNs($prefix, 'SomeRequest', null);
    $xml->writeElementNs($prefix, 'SchemaVersion', null, "2.0");
    $xml->startElementNs($prefix, 'SomeComplexType', null);
        $xml->writeElementNs($prefix, 'MessageId', null, 11);
        $xml->writeElementNs($prefix, 'Timestamp', null, '2013-07-05T14:43:43.649-04:00');
        $xml->startElementNs($prefix, 'Authentication', null);
            $xml->writeAttribute('SomeAttribute', '12312');
            $xml->writeElementNs($prefix, 'UserId', null, 'myUser');
            $xml->writeElementNs($prefix, 'Password', null, 'somePass');
        $xml->endElement();
    $xml->endElement();
$xml->endElement();

$request = new SoapVar($xml->outputMemory(), XSD_ANYXML);

$result = $this->call('submit', $request);

结果:

<?xml version="1.0" encoding="UTF-8"?> 
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://xml.somehost.com/XMLSchema/Connect">
   <SOAP-ENV:Body>
      <ns1:SomeRequest>
         <ns1:SchemaVersion>2.0</ns1:SchemaVersion>
         <ns1:SomeComplexType>
            <ns1:MessageId>11</ns1:MessageId>
            <ns1:Timestamp>2013-07-05T14:43:43.649-04:00</ns1:Timestamp>
            <ns1:Authentication SomeAttribute='12312'>
               <ns1:UserId>myUser</ns1:UserId>
               <ns1:Password>somePass</ns1:Password>
            </ns1:Authentication>
         </ns1:SomeComplexType>
      </ns1:SomeRequest>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>