phparraysfunctionmultiple-return-values

How to isolate elements in a 2-element array returned from a function?


I am using a PHP function that will return 2 arrays. Below is my function:

function imserv($id){
    $xml = simplexml_load_file("feed.xml");
    $images = $xml->xpath('//IMAGE');
    $services=$xml->xpath('//SERVICES');

    return array ($images,$services);
}

I use the below code to get results from the services block:

$services = imgserv('5874');

foreach ($services as $servicerow)
{   
    var_dump($servicerow);
}

The problem is that when it try to get only the values of the services, it returns both, services and images together. I need to to use both in two different places so how do I separate it to be used differently?

Below is my feed XML:

<?xml version="1.0" ?>
<FOUND>
<NFO>
<IMAGES>
    <IMAGE>
      <SMALL>images/small.jpg</SMALL> 
      <MED>images/med.jpg</MED> 
      <LARGE>images/large.jpg</LARGE> 
      <EXTRAL>images/extra.jpg</EXTRAL> 
    </IMAGE>
    <IMAGE>
      <SMALL>images1/small.jpg</SMALL> 
      <MED>images1/med.jpg </MED> 
      <LARGE>images1/large.jpg</LARGE> 
      <EXTRAL>images1/extra.jpg</EXTRAL> 
    </IMAGE>
    <IMAGE>
      <SMALL>images2/small.jpg</SMALL> 
      <MED>images2/med.jpg </MED> 
      <LARGE>images2/large.jpg</LARGE> 
      <EXTRAL>images2/extra.jpg</EXTRAL> 
      </IMAGE>
   </IMAGES>

<SERVICES>
<GROUP><GROUPNAME>Officials</GROUPNAME><SERVICE>
<TYPE>Handy</TYPE>
<NB>0</NB>
</SERVICE>
<SERVICE>
<TYPE>Bedroom</TYPE>
<NB>0</NB>
</SERVICE>
<SERVICE>
<TYPE>Meeting Rooms</TYPE>

<NB>0</NB>
</SERVICE>
<SERVICE>
<TYPE>Conferencing</TYPE>
<NB>0</NB>
</SERVICE>
<SERVICE>
<TYPE>Offices</TYPE>
<NB>0</NB>
</SERVICE>
</GROUP>
<GROUP><GROUPNAME>Reception</GROUPNAME><SERVICE>

<TYPE>Support</TYPE>
<NB>0</NB>
</SERVICE>
<SERVICE>
<TYPE>Reception</TYPE>
<NB>0</NB>
</SERVICE>
<SERVICE>
<TYPE>Telephone</TYPE>
<NB>0</NB>
</SERVICE>

</GROUP>
<GROUP><GROUPNAME>Authent</GROUPNAME><SERVICE>
<TYPE>Cams</TYPE>
<NB>0</NB>
</SERVICE>
</GROUP>
<GROUP><GROUPNAME>IT</GROUPNAME><SERVICE>
<TYPE>Internet</TYPE>
<NB>0</NB>
</SERVICE>
<SERVICE>
<TYPE>Telephone System</TYPE>

<NB>0</NB>
</SERVICE>
</GROUP>
<GROUP><GROUPNAME>Amenities</GROUPNAME>
<SERVICE>
<TYPE>24/7</TYPE>
<NB>0</NB>
</SERVICE>
<SERVICE>
<TYPE>AC</TYPE>
<NB>0</NB>
</SERVICE>

</GROUP>
</SERVICES>
</NFO>
</FOUND>

Solution

  • It would be easier if You change function to something like this:

    function imserv($id){
    $a = array();
    $xml=simplexml_load_file("feed.xml");
    
    $a['images']=$xml->xpath('//IMAGE');
    $a['services']=$xml->xpath('//SERVICES');
    
    return $a;
    }
    

    Then You will be able to write something like this

    $imservarr=imgserv('5874');
    foreach ($imservarr['services'] as $servicerow)
    {   
    var_dump($servicerow);    
    }
    foreach ($imservarr['images'] as $imagerow)
    {   
    var_dump($imagerow);    
    }