Parse XML response from PHP CURL

11,348

It looks like there are two problems with $xml->TwilioResponse->call.

  1. $xml contains the TwilioResponse element (the "document element"), $xml->TwilioResponse is incorrect.
  2. (XML and) SimpleXML element names are case-sensitive, call should be Call.

Give $xml->Call a spin.

Share:
11,348
ackerchez
Author by

ackerchez

Updated on June 04, 2022

Comments

  • ackerchez
    ackerchez almost 2 years

    I am trying to use an API that returns the following structure

        <TwilioResponse>
         <Call>
         <Sid>CAe1644a7eed5088b159577c5802d8be38</Sid>
         <DateCreated>Tue, 10 Aug 2010 08:02:17 +0000</DateCreated>
         <DateUpdated>Tue, 10 Aug 2010 08:02:47 +0000</DateUpdated>
         <ParentCallSid/>
         <AccountSid>AC5ef872f6da5a21de157d80997a64bd33</AccountSid>
         <To>+14153855708</To>
         <From>+14158141819</From>
         <PhoneNumberSid></PhoneNumberSid>
         <Status>completed</Status>
         <StartTime>Tue, 10 Aug 2010 08:02:31 +0000</StartTime>
         <EndTime>Tue, 10 Aug 2010 08:02:47 +0000</EndTime>
         <Duration>16</Duration>
         <Price>-0.03000</Price>
         <Direction>outbound-api</Direction>
        </Call>
       </TwilioResponse>
    

    I can get to the XML data by using CURL which works fine like this:

        $handle = curl_init();
        curl_setopt($handle, CURLOPT_URL, $base_url."/Accounts/{$accountSid}/Calls");
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($handle);
        curl_close($handle);
    

    however once I get the data back as XML I try and put it into a simpleXML element and return it back to the page that called this function as follows:

        $xml = new SimpleXmlElement($response);
        if($xml)
    {
      return $xml;
    }
    else
    {
      return false;
    }
    

    When I return the XML to the page that called the function, I can see a whole lot of simpleXMLElement Objects if I do a print_r() but when I try and do a foreach($xml->TwilioResponse->call as $call) I get nothing and it does not seem like I can actually drill into the data at all.

    Can someone help me and point out where I am going wrong with this? It has been driving me absolutely crazy for the past couple of hours.

    THANKS!

  • ackerchez
    ackerchez over 12 years
    AH! My savior! Thanx so much!