将XML解析为PHP不会返回完整数组

时间:2014-08-02 20:45:13

标签: php arrays xml simplexml

我有以下XML响应,我想解析为数组:

$response = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns="http://www.google.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="dominx.xsd">
<command>
<create>
<domain:create
xmlns:domain="http://www.google.com"
xsi:schemaLocation="domain-2.0.xsd">
<domain:name>xxxx</domain:name>
<domain:ns>xxxx</domain:ns>
<domain:ns>ns1.xxxx</domain:ns>
<domain:registrant>xxxx</domain:registrant>
<domain:contact type="tech">xxxxx</domain:contact>
<domain:authInfo>
<domain:pw>xxxx</domain:pw>
</domain:authInfo>
</domain:create>
</create>
</command>
</epp>';

function object2array($object) { return @json_decode(@json_encode($object),1); };
$xml = simplexml_load_string($response);
$xml_array=object2array($xml); 

上面我得到空阵列 - &gt; [create] => Array ( )

我想在$xml_array中获得完整数组。是否可以使用simplexml获取此XML,或者我应该以某种方式拆分此XML?

1 个答案:

答案 0 :(得分:0)

不,你不需要拆分它。您必须使用->children(),然后提供命名空间。例如:

$response = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns="http://www.google.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="dominx.xsd">
    <command>
        <create>
            <domain:create xmlns:domain="http://www.google.com" xsi:schemaLocation="domain-2.0.xsd">
                <domain:name>xxxx</domain:name>
                <domain:ns>xxxx</domain:ns>
                <domain:ns>ns1.xxxx</domain:ns>
                <domain:registrant>xxxx</domain:registrant>
                <domain:contact type="tech">xxxxx</domain:contact>
                <domain:authInfo>
                    <domain:pw>xxxx</domain:pw>
                </domain:authInfo>
            </domain:create>
        </create>
    </command>
</epp>';

$xml = simplexml_load_string($response);
$domain = $xml->command->create->children('domain', 'http://www.google.com');
echo '<pre>';
print_r($domain);

应该输出:

SimpleXMLElement Object
(
    [create] => SimpleXMLElement Object
        (
            [name] => xxxx
            [ns] => Array
            (
                [0] => xxxx
                [1] => ns1.xxxx
            )

            [registrant] => xxxx
            [contact] => xxxxx
            [authInfo] => SimpleXMLElement Object
            (
                [pw] => xxxx
            )
        )
)