XML to PHP classes
PHP reads XML easily with SimpleXML or DOMDocument, but both return loosely typed objects where every value is a string. This XML to PHP generator writes classes with typed properties from a sample document, so your application can convert an XML response once and then rely on int, bool and nested objects.
Example: an API response
<response status="ok">
<user id="17" admin="false">
<email>ada@example.com</email>
<zip>01234</zip>
</user>
</response>
class Response {
private User $user; // json:user Required
private string $status; // json:status Required
// constructor, from(), to(), validate(), getters ...
}
class User {
private string $email; // json:email Required
private int $zip; // json:zip Required
private int $id; // json:id Required
private bool $admin; // json:admin Required
}
The ZIP code problem
Look at $zip: the value 01234 looked like a number, so it was typed int, and as an integer it would be 1234. Postal codes, phone numbers, account numbers and ISBNs are identifiers, not quantities; change their types to string before using the class. This is the most common adjustment after generating classes from XML.
Filling the classes from SimpleXML
$xml = simplexml_load_string($body);
$u = $xml->user;
$user = new User(
(string) $u->email,
(string) $u->zip, // after changing $zip to string
(int) $u['id'], // attributes via array access
((string) $u['admin']) === 'true',
);
SimpleXML exposes attributes with array syntax and child elements as properties, and every value must be cast. Note that (bool) 'false' is true in PHP, so compare the string instead. A popular shortcut, json_decode(json_encode($xml)), puts attributes under an @attributes key, which differs from the shape the generated from() methods expect; either adjust the keys or construct objects directly as above. When loading XML from untrusted sources, do not pass the LIBXML_NOENT flag, which enables entity substitution.
DOMDocument for complex documents
For documents with namespaces or when you need XPath, DOMDocument with DOMXPath gives more control than SimpleXML. The generated classes work the same way: query the values, cast them, and pass them to the constructors.
How the XML is mapped
Attributes and child elements become properties of the same class, element text beside attributes becomes $value, repeated elements become arrays, and namespace prefixes are removed. The root element name (response) becomes the class name Response.
Format the generated code with the PHP Formatter. For JSON APIs use JSON to PHP. Generation runs in your browser.