Search code examples
phpxmlsimplexml

Getting values from simplexmlelement object


I'm having trouble with converting my simplexmlelement object to variables. This is my xml output:

<affiliate_signup_response>
  <success>false</success>
  <message>Duplicate Affiliate Contact</message>
  <affiliate_id>0</affiliate_id>
</affiliate_signup_response>

Now i've searched the net and found out that I have to do something like this to get the output:

(string) $xml[0]->succes;
(string) $xml->succes;
(string) $xml->affiliate_signup_response->succes;

I just can't seem to get the right response and am probaly missing the right clue into making this work. I really hope this is not a dumb question.

If create a foreach loop with $key and $value this is the output:

key: success value: false
key: message value: Duplicate Affiliate Contact
key: affiliate_id value: 0

Solution

  • Try

    $str = <<<XML
    <affiliate_signup_response>
      <success>false</success>
      <message>Duplicate Affiliate Contact</message>
      <affiliate_id>0</affiliate_id>
    </affiliate_signup_response>
    XML;
    
    
    $xml = new SimpleXMLElement($str);
    //var_dump($xml);
    $success = $xml->success;
    $message = $xml->message;
    $affiliate_id = $xml->affiliate_id;
    
    echo $success."<br />";
    echo $message."<br />";
    echo $affiliate_id."<br />";