解析XML请求

时间:2013-01-07 08:00:14

标签: php xml soap

我非常擅长处于服务器端。我需要设置一个简单的server.php来接收xml请求。

我甚至不确定如何从这开始。我已经习惯了表单中的普通Post / Get变量。

这是我正在倾听的一个例子,需要回复:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
 SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <authenticate xmlns="http://someplace.someplace.com/">
            <strUserName xsi:type="xsd:string">username</strUserName>
            <strPassword xsi:type="xsd:string">password</strPassword>
        </authenticate>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

显然我可以在里面看到一个用户名/密码 验证用户/通行证是一件容易的事,但我该如何解析呢?

3 个答案:

答案 0 :(得分:0)

尝试使用SimpleXML,这里有几个例子:

SimpleXML examples

答案 1 :(得分:0)

您还可以使用DOM元素访问所需的值:

$xml = '<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
 SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <authenticate xmlns="http://someplace.someplace.com/">
            <strUserName xsi:type="xsd:string">username</strUserName>
            <strPassword xsi:type="xsd:string">password</strPassword>
        </authenticate>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>';

$dom = new DOMDocument();
$dom->loadXML( $xml );

$username = $dom->getElementsByTagName('strUserName')->item(0)->nodeValue;
$password = $dom->getElementsByTagName('strPassword')->item(0)->nodeValue;

答案 2 :(得分:0)

解析SOAP请求时,您应该使用现有的API。这不仅会自动消除您的解析问题,还会生成正确的SOAP输出。

示例:

$request = '<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
 SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <authenticate xmlns="http://someplace.someplace.com/">
            <strUserName xsi:type="xsd:string">foo</strUserName>
            <strPassword xsi:type="xsd:string">bar</strPassword>
        </authenticate>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>';

$s = new SoapServer(NULL, array('uri' => 'http://someplace.someplace.com/'));
$s->setClass("Auth");
$s->handle($request);

class Auth
{
    public function authenticate($strUserName, $strPassword)
    {
        return "U: $strUserName; P: $strPassword";
    }
}

注意:如果您未将参数传递给handle(),则会使用POST数据。