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>[email protected]</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

}
1

1 Answer 1

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 
}
Sign up to request clarification or add additional context in comments.

1 Comment

I will try this approach and post the result here. Thanks very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.