Search code examples
phpxmlsoapsoap-client

Soap xml is passing reference in php


I am calling a webservice using soap in php but I am getting the error in xml as response from the server.

The problem is that when creating the xml for the request Php introduces the id in the xml and then wherever it finds the same node it just passes the id as the reference.

Eg:-

<ns1:ChargeBU id=\"ref1\">
<ns1:ChargeBreakUp>
<ns1:PriceId>0</ns1:PriceId>
<ns1:ChargeType>TboMarkup</ns1:ChargeType>
<ns1:Amount>35</ns1:Amount>
</ns1:ChargeBreakUp><ns1:ChargeBreakUp>
<ns1:PriceId>0</ns1:PriceId>
<ns1:ChargeType>OtherCharges</ns1:ChargeType>
<ns1:Amount>0.00</ns1:Amount>
</ns1:ChargeBreakUp>
</ns1:ChargeBU>

and then when it finds the same node it does this

<ns1:ChargeBU href=\"#ref1\"/>

So how can i prevent this so that it includes the full node again instead of just passing the reference ??


Solution

  • you can create a new copy (instance) of that array to prevent php to use refs for the same values.

    for example, we have:

    $item = array(
        "id" => 1,
        "name" => "test value"
    );
    

    and our request/response:

    $response = array(
        "item1" => $item,
        "item2" => $item
    );
    

    by default, php will replace item2 value with reference to item1 (both items point to the same array)

    in order to prevent such behaviour, we need to create two different items with the same structure, something like:

    function copyArray($source){
        $result = array();
    
        foreach($source as $key => $item){
            $result[$key] = (is_array($item) ? copyArray($item) : $item);
        }
    
        return $result;
    }
    

    and request/response:

    $response = array(
        "item1" => copyArray($item),
        "item2" => copyArray($item)
    );
    

    the same by structure items are in fact different arrays in memory and php will not generate any refs in this case