So you found yourself looking for one of the following keywords ‘PHP SOAP Repeated Element Name‘ or ‘SOAP Structure Repeated Name‘.
Then look no further, I’m going to show you how to properly address this problem.
PHP SoapClient is not the most complete library out there, it’s actually rather poor at times, if you have the time to test and implement, a better, faster, more complete library to replace PHP SoapClient, then google this: WSO2 Web Services Framework for PHP (WSO2 WSF/PHP), it’s a paid-turned-open source project.
In reference to our problem, you may have a structure like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
<Competition> <Dogs> <Dog> <Gender>Male</Gender> <Breed>Aidi</Breed> </Dog> <Dog> <Gender>Female</Gender> <Breed>Labrador</Breed> </Dog> </Dogs> </Competition> |
And whether you are building the response using Objects or Arrays, the answer is pretty much the same.
In case you are working with a complex WSDL Specification you are probably using Objects, for perfect control over the namespaces.
The Solution
The simplest solution relies on a pretty little thing called, ArrayObject, implemented in PHP 5, which can be used whether you are building an Array or an Object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Note, this is a method which can be used in simple and complex responses $dogParams = new ArrayObject(); // Dog Parameters $dogs = new ArrayObject(); // Dog Element $Competition = new stdClass(); // Competition Element // * Note the hard-coded 0, because this is an example $dogParams[0]->Gender = 'Male'; $dogParams[0]->Breed = 'Aidi'; // If you are building a complex response, you could have gone for this // example using a SoapVar $dogParams[1]->Gender = new SoapVar("Female", XSD_STRING, NULL, $namespace, 'Gender', $namespace); $dogParams[1]->Breed= new SoapVar("Labrador", XSD_STRING, NULL, $namespace, 'Breed', $namespace); // Now that we have two (2) dogs information, create Dog object $dog=[]; $dog[0] = new SoapVar($dogParams[0],SOAP_ENC_OBJECT,NULL,$namespace,'Dog',$namespace); $dog[1] = new SoapVar($dogParams[1],SOAP_ENC_OBJECT,NULL,$namespace,'Dog',$namespace); // and append it to Dogs $dogs->append($dog[0]); $dogs->append($dog[1]); // And now our outside structure, Competition element $competition->Dogs = new SoapVar($dogs, SOAP_ENC_OBJECT, NULL, $namespace, 'Dogs ', $namespace); |
If you are a building simple response without need for namespace declarations, you can just put the value instead of using SoapVar’s.
The example above will output the XML repeated element example above when sent via SOAP.