title: PHP json_encode on a SOAP response returns array if multiple, but object if single?
body: <p>I have a Windows Desktop Gadget that, for a small number of my users, suddenly stopped working a few months back.  Seemed to be that they suddenly didn't like cross-domain requests (even though all servers are on our intranet here).   So, I'm rewriting the thing so that it goes to a single backend server that I have a lot of control over... and its Ajax queries to the backend are set to use data Type: jsonp.     Meanwhile, the php script that the gadget queries a la Ajax calls a SOAP service, gets the data back, turns it into an array, and then uses json_encode to turn it into a string and add a reference to a callback function on the Gadget / javascript side. </p>
  
  <p>My problem seems to be with json_encode.   If the SOAP response includes a single data record, it sends it as an object.  If the SOAP response contains multiple records, it's slapping brackets around it, like an array.</p>
  
  <p>Examples:</p>
  
  <p>Single record:</p>
  
  <pre><code>`{
    "SmeDetail": {
      "SipAddress": "jane.smith@whatever.com",
      "SubjectExpert": "Smith,Jane",
      "SubjectMatter": "Unix"
    }
  }`
  </code></pre>
  
  <p>Multiple records:</p>
  
  <pre><code>`{
    "SmeDetail": [
      {
        "SipAddress": "fred.flintstone@whatever.com",
        "SubjectExpert": "Flintstone,Fred",
        "SubjectMatter": "Bedrock"
      },
      {
        "SipAddress": "barney.rubble@whatever.com",
        "SubjectExpert": "Rubble,Barney",
        "SubjectMatter": "Bedrock"
      },
      {
        "SipAddress": "wilma.flintstone@whatever.com",
        "SubjectExpert": "Flintsone,Wilma",
        "SubjectMatter": "Bedrock"
      }
    ]
  }`
  </code></pre>
  
  <p>In the php script, a typical SOAP call goes like this:</p>
  
  <pre><code>$Service_URL = 'http://server/PROD/OurWcfService/WcfService.svc?wsdl';
  $client = new SoapClient($Service_URL);
  $res= $client-&gt;GetSMEDetails($params)-&gt;GetSMEDetailsResult;
  </code></pre>
  
  <p>and then $res is fed to this routine:</p>
  
  <pre><code>$json_data = json_encode((array)$res);
  echo $_GET['callback_name'].'('.$json_data.');';
  </code></pre>
  
  <p>And that echo is what's fed back as the Ajax response.</p>
  
  <p>I'm not sure where I even read about using this json_encode((array)$res) to do the conversion from the Soap response into an array, then the json encoded string.   But I'm wondering if I'm doing something wrong here?   I guess I need to make sure that single records are pushed through as an array.   And I'd rather fix that the "right way" rather than do some sort of hack on the string.</p>
  
  <p>Any thoughts?</p>