### Install XSD2PHP via Composer
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Add the runtime and development dependencies to your composer.json file.
```json
{
"require": {
"goetas-webservices/xsd2php-runtime": "^0.2.2"
},
"require-dev": {
"goetas-webservices/xsd2php": "^0.3"
}
}
```
--------------------------------
### Install xsd2php via Composer
Source: https://github.com/goetas-webservices/xsd2php/blob/master/README.md
Add the runtime and development dependencies to your project's composer.json file.
```json
"require": {
..
"goetas-webservices/xsd2php-runtime":"^0.2.2",
..
},
"require-dev": {
..
"goetas-webservices/xsd2php":"^0.3",
..
},
```
--------------------------------
### Generated PHP Class Structure
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Example of a generated PHP class demonstrating private properties, fluent setters, and typed getters.
```php
transactionIdentifier;
}
/**
* Sets a new transactionIdentifier
*
* @param string $transactionIdentifier
* @return self
*/
public function setTransactionIdentifier($transactionIdentifier)
{
$this->transactionIdentifier = $transactionIdentifier;
return $this;
}
/**
* Gets as departureDate
*
* @return \DateTime
*/
public function getDepartureDate()
{
return $this->departureDate;
}
/**
* Sets a new departureDate
*
* @param \DateTime $departureDate
* @return self
*/
public function setDepartureDate(\DateTime $departureDate = null)
{
$this->departureDate = $departureDate;
return $this;
}
/**
* Adds as passenger
*
* @param \MyApp\Api\PassengerType $passenger
* @return self
*/
public function addToPassengers(\MyApp\Api\PassengerType $passenger)
{
$this->passengers[] = $passenger;
return $this;
}
/**
* isset passengers
*
* @param int|string $index
* @return bool
*/
public function issetPassengers($index)
{
return isset($this->passengers[$index]);
}
/**
* unset passengers
*
* @param int|string $index
* @return void
*/
public function unsetPassengers($index)
{
unset($this->passengers[$index]);
}
/**
* Gets as passengers
*
* @return \MyApp\Api\PassengerType[]
*/
public function getPassengers()
{
return $this->passengers;
}
/**
* Sets a new passengers
*
* @param \MyApp\Api\PassengerType[] $passengers
* @return self
*/
public function setPassengers(array $passengers)
{
$this->passengers = $passengers;
return $this;
}
}
```
--------------------------------
### Generate PHP Classes and Metadata
Source: https://github.com/goetas-webservices/xsd2php/blob/master/README.md
Execute the conversion command using a configuration file and target XSD files.
```sh
vendor/bin/xsd2php convert config.yml /home/my/ota/OTA_Air*.xsd
```
--------------------------------
### Convert XSD to PHP via CLI
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Execute the conversion process using the command-line interface with various file selection patterns.
```bash
# Convert a single XSD file
vendor/bin/xsd2php convert config.yml schemas/api.xsd
# Convert multiple XSD files using glob patterns
vendor/bin/xsd2php convert config.yml schemas/*.xsd
# Convert specific XSD files from a directory
vendor/bin/xsd2php convert config.yml \
schemas/OTA_AirAvailRQ.xsd \
schemas/OTA_AirAvailRS.xsd \
schemas/OTA_AirBookRQ.xsd
# Convert all XSD files matching a pattern
vendor/bin/xsd2php convert config.yml /path/to/schemas/OTA_*.xsd
```
--------------------------------
### Configure XSD2PHP with YAML
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Define namespace mappings, output directories, and optional settings in a YAML configuration file.
```yaml
# config.yml
xsd2php:
# Map XML namespaces to PHP namespaces (required)
namespaces:
'http://www.example.org/api/': 'MyApp\Api'
'http://www.example.org/common/': 'MyApp\Common'
# Output directories for generated PHP classes (required)
destinations_php:
'MyApp\Api': src/Api
'MyApp\Common': src/Common
# Output directories for JMS Serializer metadata (required)
destinations_jms:
'MyApp\Api': config/serializer/Api
'MyApp\Common': config/serializer/Common
# Output directories for Symfony Validator metadata (optional)
destinations_validation:
'MyApp\Api': config/validation/Api
'MyApp\Common': config/validation/Common
# Custom type aliases for XSD types (optional)
aliases:
'http://www.example.org/api/':
CustomDateType: 'MyApp\Types\CustomDate'
MoneyType: 'MyApp\Types\Money'
# Naming strategy: 'short' (default) or 'long'
naming_strategy: short
# Path generator strategy: 'psr4' (default)
path_generator: psr4
# Override remote schema locations with local files (optional)
known_locations:
'http://www.example.org/schemas/common.xsd': schemas/local/common.xsd
# Specify schema location by namespace (optional)
known_namespace_locations:
'urn:example:common-1.0': schemas/common-1.0.xsd
# JMS Serializer specific configuration (optional)
configs_jms:
xml_cdata: false # Disable CDATA wrapping in serialization
```
--------------------------------
### Configure xsd2php with YAML
Source: https://github.com/goetas-webservices/xsd2php/blob/master/README.md
Define namespace mappings and destination directories for generated PHP classes and metadata in a configuration file.
```yaml
# config.yml
# Linux Users: PHP Namespaces use back slash \ rather than a forward slash /
# So for destinations_php, the namespace would be TestNs\MyApp
xsd2php:
namespaces:
'http://www.example.org/test/': 'TestNs\MyApp'
destinations_php:
'TestNs\MyApp': soap/src
# 'TestNs\MyApp': soap\src # on Windows
destinations_jms:
'TestNs\MyApp': soap/metadata
# 'TestNs\MyApp': soap/metadata # on Windows
# Uncomment this section if you want to have also symfony/validator metadata to be generated from XSD
# destinations_validation:
# 'TestNs\MyApp': soap/validation
# 'TestNs\MyApp': soap/validation # on Windows
aliases: # optional
'http://www.example.org/test/':
MyCustomXSDType: 'MyCustomMappedPHPType'
naming_strategy: short # optional and default
path_generator: psr4 # optional and default
# known_locations: # optional
# "http://www.example.org/test/somefile.xsd": somefile.xsd
# known_namespace_locations: # optional
# "urn:veloconnect:catalog-1.1": xsd/catalog-1.1.xsd
# configs_jms: #optional
```
--------------------------------
### Configure xsd2php namespaces and aliases
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Define namespace mappings, output directories, and custom handlers for XML Schema types in your configuration file.
```yaml
xsd2php:
namespaces:
'http://www.example.org/api/': 'MyApp\Api'
destinations_php:
'MyApp\Api': src/Api
destinations_jms:
'MyApp\Api': config/serializer/Api
# Map anyType to your custom handler class
aliases:
'http://www.w3.org/2001/XMLSchema':
anyType: 'MyApp\Handlers\AnyTypeHandler'
anySimpleType: 'MyApp\Handlers\AnySimpleTypeHandler'
```
--------------------------------
### Configure JMS Serializer
Source: https://github.com/goetas-webservices/xsd2php/blob/master/README.md
Set up the JMS Serializer with custom handlers for XML schema types and metadata directories.
```php
addMetadataDir('metadata dir', 'TestNs');
$serializerBuilder->configureHandlers(function (HandlerRegistryInterface $handler) use ($serializerBuilder) {
$serializerBuilder->addDefaultHandlers();
$handler->registerSubscribingHandler(new BaseTypesHandler()); // XMLSchema List handling
$handler->registerSubscribingHandler(new XmlSchemaDateHandler()); // XMLSchema date handling
// $handler->registerSubscribingHandler(new YourhandlerHere());
});
$serializer = $serializerBuilder->build();
// deserialize the XML into Demo\MyObject object
$object = $serializer->deserialize('', 'TestNs\MyObject', 'xml');
// some code ....
// serialize the Demo\MyObject back into XML
$newXml = $serializer->serialize($object, 'xml');
```
--------------------------------
### YAML Configuration for Short Naming Strategy
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Configure xsd2php to use the 'short' naming strategy, which is the default. This strategy influences how PHP class names are generated from XSD types.
```yaml
# config.yml - Short naming strategy (default)
xsd2php:
naming_strategy: short
namespaces:
'http://www.example.org/api/': 'MyApp\Api'
destinations_php:
'MyApp\Api': src/Api
destinations_jms:
'MyApp\Api': config/serializer/Api
# With short naming:
# XSD type "User" becomes "UserType" (if doesn't already end with "Type")
# XSD type "UserType" stays "UserType"
# Anonymous types become "ParentNameAType"
```
--------------------------------
### Programmatic XSD to PHP Conversion with PhpConverter
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Use the PhpConverter class for programmatic conversion of XSD schemas to PHP class definitions. This involves reading the schema, configuring the converter, and generating/writing the PHP files.
```php
readFile('schemas/api.xsd');
// Create converter with naming strategy
$namingStrategy = new ShortNamingStrategy();
$converter = new PhpConverter($namingStrategy);
// Add namespace mappings
$converter->addNamespace('http://www.example.org/api/', 'MyApp\Api');
$converter->addNamespace('http://www.example.org/common/', 'MyApp\Common');
// Add custom type aliases
$converter->addAliasMapType(
'http://www.example.org/api/',
'CustomDateType',
'MyApp\Types\CustomDate'
);
// Convert schemas to PHP class definitions
$phpClasses = $converter->convert([$schema]);
// Generate actual PHP code
$classGenerator = new ClassGenerator();
$generatedClasses = [];
foreach ($phpClasses as $phpClass) {
$generated = $classGenerator->generate($phpClass);
if ($generated !== null) {
$generatedClasses[] = $generated;
}
}
// Write PHP files
$pathGenerator = new Psr4PathGenerator([
'MyApp\Api' => 'src/Api',
'MyApp\Common' => 'src/Common'
]);
$writer = new PHPClassWriter($pathGenerator);
$writer->write($generatedClasses);
echo "Generated " . count($generatedClasses) . " PHP classes.\n";
```
--------------------------------
### Define Custom Serialization Handler in PHP
Source: https://github.com/goetas-webservices/xsd2php/blob/master/README.md
Implement SubscribingHandlerInterface to define custom serialization and deserialization methods for specific types. Ensure the class is correctly registered in config.yml.
```php
use JMS\Serializer\XmlSerializationVisitor;
use JMS\Serializer\XmlDeserializationVisitor;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\VisitorInterface;
use JMS\Serializer\Context;
class MyHandler implements SubscribingHandlerInterface
{
public static function getSubscribingMethods()
{
return array(
array(
'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
'format' => 'xml',
'type' => 'MyCustomAnyTypeHandler',
'method' => 'deserializeAnyType'
),
array(
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'xml',
'type' => 'MyCustomAnyTypeHandler',
'method' => 'serializeAnyType'
)
);
}
public function serializeAnyType(XmlSerializationVisitor $visitor, $data, array $type, Context $context)
{
// serialize your object here
}
public function deserializeAnyType(XmlDeserializationVisitor $visitor, $data, array $type)
{
// deserialize your object here
}
}
```
--------------------------------
### YAML Configuration for Long Naming Strategy
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Configure xsd2php to use the 'long' naming strategy. This strategy generates PHP class names that are more verbose and can help avoid naming conflicts.
```yaml
# config.yml - Long naming strategy
xsd2php:
naming_strategy: long
namespaces:
'http://www.example.org/api/': 'MyApp\Api'
destinations_php:
'MyApp\Api': src/Api
destinations_jms:
'MyApp\Api': config/serializer/Api
# With long naming:
# XSD type "User" becomes "UserType"
# XSD type "UserType" becomes "UserTypeType"
# Anonymous types become "ParentNameAnonymousPHPType"
# XSD element "User" becomes "UserElement"
# Use long naming when you have conflicts like:
# - Type named "User" AND element named "User"
# - Type named "UserType" AND type named "User"
```
--------------------------------
### Implement a custom JMS Serializer handler
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Create a class implementing SubscribingHandlerInterface to handle custom serialization and deserialization logic for specific types.
```php
GraphNavigator::DIRECTION_DESERIALIZATION,
'format' => 'xml',
'type' => 'MyApp\Handlers\AnyTypeHandler',
'method' => 'deserializeAnyType'
],
[
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'xml',
'type' => 'MyApp\Handlers\AnyTypeHandler',
'method' => 'serializeAnyType'
]
];
}
public function deserializeAnyType(
XmlDeserializationVisitor $visitor,
\SimpleXMLElement $data,
array $type
): mixed {
// Convert XML element to array for flexible handling
$result = [];
foreach ($data->attributes() as $key => $value) {
$result['@' . $key] = (string) $value;
}
foreach ($data->children() as $child) {
$childName = $child->getName();
if (isset($result[$childName])) {
if (!is_array($result[$childName]) || !isset($result[$childName][0])) {
$result[$childName] = [$result[$childName]];
}
$result[$childName][] = $this->elementToArray($child);
} else {
$result[$childName] = $this->elementToArray($child);
}
}
if (empty($result) && (string) $data !== '') {
return (string) $data;
}
return $result;
}
public function serializeAnyType(
XmlSerializationVisitor $visitor,
mixed $data,
array $type,
Context $context
): \DOMElement {
$document = $visitor->getDocument();
$element = $document->createElement('anyType');
if (is_array($data)) {
foreach ($data as $key => $value) {
if (str_starts_with($key, '@')) {
$element->setAttribute(substr($key, 1), $value);
} else {
$child = $document->createElement($key);
$child->appendChild($document->createTextNode((string) $value));
$element->appendChild($child);
}
}
} else {
$element->appendChild($document->createTextNode((string) $data));
}
return $element;
}
private function elementToArray(\SimpleXMLElement $element): mixed
{
$children = $element->children();
if (count($children) === 0) {
return (string) $element;
}
$result = [];
foreach ($children as $child) {
$childName = $child->getName();
$result[$childName] = $this->elementToArray($child);
}
return $result;
}
}
```
--------------------------------
### Serialize PHP Objects to XML with JMS Serializer
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Uses the same configuration as deserialization to convert populated PHP objects back into XML format.
```php
addMetadataDir('config/serializer/Api', 'MyApp\Api');
$serializerBuilder->configureHandlers(function (HandlerRegistryInterface $handler) use ($serializerBuilder) {
$serializerBuilder->addDefaultHandlers();
$handler->registerSubscribingHandler(new BaseTypesHandler());
$handler->registerSubscribingHandler(new XmlSchemaDateHandler());
});
$serializer = $serializerBuilder->build();
// Create and populate PHP object
$response = new \MyApp\Api\AirAvailRS();
$response->setTransactionIdentifier('TXN-12345');
$response->setTimeStamp(new \DateTime('2024-06-15T14:30:00'));
// Add flight options
$flightOption = new \MyApp\Api\FlightOptionType();
$flightOption->setFlightNumber('AA100');
$flightOption->setDepartureTime(new \DateTime('2024-06-15T10:30:00'));
$flightOption->setArrivalTime(new \DateTime('2024-06-15T13:45:00'));
$flightOption->setPrice(450.00);
$flightOption->setCurrency('USD');
$response->addToFlightOptions($flightOption);
// Serialize to XML
$xmlOutput = $serializer->serialize($response, 'xml');
echo $xmlOutput;
// Output:
//
//
// TXN-12345
// 2024-06-15T14:30:00+00:00
//
// AA100
// 2024-06-15T10:30:00+00:00
// 2024-06-15T13:45:00+00:00
// 450
// USD
//
//
```
--------------------------------
### Deserialize XML to PHP Objects with JMS Serializer
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Configures the SerializerBuilder with metadata directories and required XML Schema handlers to map XML documents to strongly-typed PHP classes.
```php
path mapping)
$serializerBuilder->addMetadataDir('config/serializer/Api', 'MyApp\Api');
$serializerBuilder->addMetadataDir('config/serializer/Common', 'MyApp\Common');
// Register required handlers for XML Schema types
$serializerBuilder->configureHandlers(function (HandlerRegistryInterface $handler) use ($serializerBuilder) {
$serializerBuilder->addDefaultHandlers();
// Handler for XMLSchema list types (xsd:list)
$handler->registerSubscribingHandler(new BaseTypesHandler());
// Handler for XMLSchema date/time types (xsd:date, xsd:dateTime, xsd:time)
$handler->registerSubscribingHandler(new XmlSchemaDateHandler());
});
$serializer = $serializerBuilder->build();
// Sample XML document
$xml = <<
2024-06-15T10:30:00
JFK
LAX
Business
XML;
// Deserialize XML into PHP object
$airAvailRequest = $serializer->deserialize($xml, 'MyApp\Api\AirAvailRQ', 'xml');
// Access typed properties
echo $airAvailRequest->getOriginLocation(); // "JFK"
echo $airAvailRequest->getDestinationLocation(); // "LAX"
echo $airAvailRequest->getDepartureDateTime()->format('Y-m-d'); // "2024-06-15"
```
--------------------------------
### Generate JMS Metadata with YamlConverter
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Use the YamlConverter class to read an XSD schema, map namespaces, and write JMS Serializer YAML metadata files.
```php
readFile('schemas/api.xsd');
// Create JMS YAML converter
$namingStrategy = new ShortNamingStrategy();
$converter = new YamlConverter($namingStrategy);
// Add namespace mappings
$converter->addNamespace('http://www.example.org/api/', 'MyApp\\Api');
// Disable CDATA wrapping in serialization output
$converter->setUseCdata(false);
// Convert schemas to JMS metadata
$jmsMetadata = $converter->convert([$schema]);
// Write YAML metadata files
$pathGenerator = new Psr4PathGenerator([
'MyApp\\Api' => 'config/serializer/Api'
]);
$writer = new JMSWriter($pathGenerator);
$writer->write($jmsMetadata);
echo "Generated " . count($jmsMetadata) . " JMS metadata files.\n";
// Example generated YAML metadata (MyApp.Api.AirAvailRQ.yml):
// MyApp\Api\AirAvailRQ:
// xml_root_name: AirAvailRQ
// xml_root_namespace: http://www.example.org/api/
// properties:
// departureDateTime:
// expose: true
// access_type: public_method
// serialized_name: DepartureDateTime
// accessor:
// getter: getDepartureDateTime
// setter: setDepartureDateTime
// type: GoetasWebservices\Xsd\XsdToPhp\XMLSchema\DateTime
```
--------------------------------
### Disable CDATA in Configuration
Source: https://github.com/goetas-webservices/xsd2php/blob/master/README.md
Set the xml_cdata flag to false within the xsd2php configuration to disable CDATA usage.
```yaml
xml_cdata: false # Disables CDATA
```
--------------------------------
### Disable CDATA in YAML Configuration
Source: https://github.com/goetas-webservices/xsd2php/blob/master/README.md
Configure the JMS settings in the YAML file to disable CDATA.
```yaml
xsd2php:
configs_jms:
xml_cdata: false
```
--------------------------------
### Validate Generated Objects
Source: https://github.com/goetas-webservices/xsd2php/blob/master/README.md
Use the Symfony Validator component to validate objects against generated YAML mapping files.
```php
addYamlMapping($file);
}
$validator = $builder->getValidator();
// validate $object
$violations = $validator->validate($object, null, ['xsd_rules']);
```
--------------------------------
### Validate PHP Objects with Symfony Validator
Source: https://context7.com/goetas-webservices/xsd2php/llms.txt
Use generated Symfony Validator metadata (YAML mappings) to validate PHP objects against XSD constraints. Ensure validation metadata files are loaded correctly.
```php
addYamlMapping($file);
}
foreach (glob('config/validation/Common/*.yml') as $file) {
$builder->addYamlMapping($file);
}
$validator = $builder->getValidator();
// Create an object to validate
$request = new \MyApp\Api\AirBookRQ();
$request->setPassengerCount(0); // Invalid: must be positive
$request->setFlightNumber(''); // Invalid: cannot be empty
// Validate using XSD rules group
$violations = $validator->validate($request, null, ['xsd_rules']);
if (count($violations) > 0) {
foreach ($violations as $violation) {
echo sprintf(
"Property '%s': %s (invalid value: %s)\n",
$violation->getPropertyPath(),
$violation->getMessage(),
json_encode($violation->getInvalidValue())
);
}
// Output:
// Property 'passengerCount': This value should be positive. (invalid value: 0)
// Property 'flightNumber': This value should not be blank. (invalid value: "")
}
// Valid object passes validation
$validRequest = new \MyApp\Api\AirBookRQ();
$validRequest->setPassengerCount(2);
$validRequest->setFlightNumber('AA100');
$validRequest->setDepartureDate(new \DateTime('2024-06-15'));
$violations = $validator->validate($validRequest, null, ['xsd_rules']);
echo count($violations) === 0 ? "Validation passed!" : "Validation failed.";
// Output: Validation passed!
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.