1

I'm a Java developer. How do I deal with an XML response using PHP?

  1. I would like to call a service HTTP (rest) that will return a XML.
  2. After getting this XML response, I would like to convert this XML into a Object (class) automatically like I've done in Java. (That is the part I don't know to cope with).

Example:

My xml:

<?xml>
<root>
<user_email>fde@xxx.com</user_email>
<user_name>FDE Test</user_name>
<password_expired>false</password_expired>
</root>

My class:

class User{

    private $_userMail;
    private $_userName;
    private $_isPasswordExpired;

    // Getters and Setters

}
Barett
  • 5,826
  • 6
  • 51
  • 55

1 Answers1

2

First you can request it with curl (and curl is not only option), here is a simple example.

And need to change your response xml to xml object with simplexml_load_string

$response = simplexml_load_string($xml_response);

You can set your response data in class construct whatever you like.

class User {
   private $_userMail;

   function __construct($response) {
       $this->setUserMail($response->userMail);
   }

   // getters, setters
}

And after you get your response, you need to create User object and give your response to that.

// Create User
$user = new User($response);
// Check if response created a valid object
if ($user instanceof User) {
    // valid 
} else {
    // not valid 
}
mim.
  • 669
  • 9
  • 18