简体   繁体   中英

Converting XML to array in PHP to call Soap API

I have a Soap API to call from a PHP code. I am having trouble converting it to array. I have searched many questions on Stackoverflow & google as well, but was not helpful enough.

I am facing problem when converting the following into array.

            <objects>
              <ABCnxtObj> 
                   xsi:type="api:Lead" 
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <Key>702144</Key>
                <Custom>
                  <BusinessName>9<BusinessName>
                  </Custom>
               </ABCnxtObj>
            </objects>

I am converting this to the following array:

$objects = [
        'ABCnxtObj' => [
            'Key' => 702144,
            'Custom' => [
                'BusinessName' => 9
            ]
        ]
    ];

The problem here is I am not able to put the xsi:type & xmlns:xsi attributes. Can anyone explain me, on how do I pass these values in my array.

Or if there is another way of doing this.

Thanks!

Use this as an example:

$data = '<objects>
            <ABCnxtObj xsi:type="api:Lead" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <Key>702144</Key>
                <Custom>
                  <BusinessName>9</BusinessName>
                </Custom>
            </ABCnxtObj>
        </objects>';


$xml = simplexml_load_string($data);
$namespaces = $xml->getNamespaces(1);

$array = [];

foreach ($xml AS $obj => $val) {

    foreach ($namespaces AS $ns => $nsv) {
        $array[$obj]['namespaces'][$ns] = $nsv;

        foreach ($xml->$obj->attributes($ns, 1) AS $name => $value) {
            $array[$obj]['attributes'][$ns.':'.$name] = (string) $value[0];
        }
    }
    $array[$obj]['object'] = $val;
}

var_dump($array);

Attribute xmlns:xsi is a namespace definition, you can read it with getNamespaces method of SimpleXMLElement object. When you know what namespaces can appear in your XML, you can read attributes under all namespaces - this is happening in internal foreach loop: walkthrough all namespaces and read all attributes within current namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM