generate PHP classes from XSD?

Viewed 40862

Is there in the world analogues of JavaBeans or JAXB for PHP? Is it possible to generate PHP classes from XML schema?

It's common practice to publish API's as XSD schemas. Java and C# guys can get advantage of this by generating classes right from XSD. Is there same tool for PHP?

8 Answers

The main reasons for using XSD class generators is to

  1. Get compile time checking
  2. An easier syntax than plain old XML API's
  3. Auto completion in your IDE.

Now contrast this with PHP. PHP does not have compile time checking and it has support for dynamic methods/properties. This voids two of the main reasons above and makes this a non-issue unless you really need auto completion. In other words, there is reason to use an XSD class generator in PHP, and that is probably also why none exist.

My suggestion is to use PHPs Simple XML which creates properties to match the XML dynamically during runtime. If you validate your XML against the XSD file and then create a Simple XML object, you have your XML object structure complete with methods and properties, without having to generate code. A perfectly good approach in PHP.

Note that I don't state that SimpleXML is the same as generated XSD classes, of course not.. But it is pretty close, usage and API-wise. You still end up doing something like $company->employee[2]->firstname either way.

This library seems to be the best choice nowadays: https://github.com/goetas/xsd2php

It generates PHP classes for XML Elements and can convert it back and forth:

XML -> PHP -> XML

I looked into that a while ago, and I certainly could not find one. If your schema is simple, there's a guy who hacked a simple version together for flat schemas.

That's all I know about. Normally these guys are good at supporting languages other than the main ones, but they don't do PHP either.

The DMS Software Reengineering Toolkit is configurable code generation machinery, that can be used to process arbitrary formal documents as input. DMS can be used to generate code in arbitary output languages.

We have used it to generate native Java and COBOL XML readers and writers from DTDs, which are the elder cousin of schemas. The same ideas would be easily applied to PHP.

Related