The data classes provide object-oriented interfaces for working with XML data. XMLElement extends SimpleXMLElement for raw XML operations, while XMLObject provides array-like access to processed XML data.
XMLElement
The XMLElement class extends PHP’s SimpleXMLElement with additional helper methods for working with XML attributes.
Class Definition
class XMLElement extends SimpleXMLElement
XMLElement inherits all methods from PHP’s SimpleXMLElement. See PHP documentation for inherited methods.
attribute()
Get an XML attribute value by name.
public function attribute(string $name, mixed $default = null): mixed
The name of the attribute to retrieve.
Default value to return if the attribute doesn’t exist.
Returns the attribute value as a string, or the default value if not found.
// XML: <user id="123" role="admin" />
$userId = $element->attribute('id'); // "123"
$role = $element->attribute('role'); // "admin"
$status = $element->attribute('status', 'active'); // "active" (default)
hasAttribute()
Check if an attribute exists.
public function hasAttribute(string $attribute): bool
The name of the attribute to check.
Returns true if the attribute exists, false otherwise.
// XML: <user id="123" name="John" />
if ($element->hasAttribute('id')) {
$id = $element->attribute('id');
}
if (!$element->hasAttribute('email')) {
// Email attribute not present
}
Usage Example
use Flowgistics\XML\Facades\XML;
// Import XML with raw mode
$xml = XML::import('users.xml', true);
// Access elements
foreach ($xml->user as $user) {
// Get attributes
$id = $user->attribute('id');
$role = $user->attribute('role', 'user');
// Check attributes
if ($user->hasAttribute('verified')) {
$verified = $user->attribute('verified');
}
// Access element values
$name = (string) $user->name;
$email = (string) $user->email;
}
XMLObject
The XMLObject class provides an array-like interface for working with processed XML data. It implements ArrayAccess, Countable, IteratorAggregate, and JsonSerializable.
Class Definition
class XMLObject implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
Constructor
new XMLObject(array $xml)
The XML data as an associative array.
$object = new XMLObject([
'name' => 'John Doe',
'email' => '[email protected]',
'@attributes' => ['id' => '123']
]);
XML attributes are automatically extracted from the @attributes key during construction.
Attribute Methods
attribute()
Get an attribute value from the XML object.
public function attribute(string $name, mixed $default = null): mixed
Default value if attribute doesn’t exist.
Returns the attribute value or default.
$userId = $xmlObject->attribute('id');
$status = $xmlObject->attribute('status', 'active');
hasAttribute()
Check if an attribute exists.
public function hasAttribute(string $attribute): bool
The attribute name to check.
Returns true if the attribute exists.
if ($xmlObject->hasAttribute('verified')) {
// Attribute exists
}
Array Access
XMLObject implements ArrayAccess for array-like operations.
offsetExists()
Check if a key exists.
public function offsetExists(mixed $offset): bool
if (isset($xmlObject['name'])) {
// Key exists
}
offsetGet()
Get a value by key.
public function offsetGet(mixed $offset): mixed
$name = $xmlObject['name'];
offsetSet()
Set a value by key.
public function offsetSet(mixed $offset, mixed $value): void
$xmlObject['name'] = 'Jane Doe';
$xmlObject[] = 'New item'; // Append
offsetUnset()
Remove a key.
public function offsetUnset(mixed $offset): void
unset($xmlObject['name']);
Magic Methods
__get()
Access items using property syntax.
public function __get(string $key): mixed
$name = $xmlObject->name;
$email = $xmlObject->email;
__set()
Set items using property syntax.
public function __set(string $key, mixed $value): void
__isset()
Check if a property exists.
public function __isset(string $name): bool
if (isset($xmlObject->name)) {
// Property exists
}
Countable Interface
count()
Count the number of items.
public function count(): int
Returns the number of items in the object.
$itemCount = count($xmlObject);
// or
$itemCount = $xmlObject->count();
IteratorAggregate Interface
getIterator()
Get an iterator for the items.
public function getIterator(): ArrayIterator
Returns an ArrayIterator instance.
foreach ($xmlObject as $key => $value) {
echo "$key: $value\n";
}
JSON Serialization
toJson()
Convert the object to a JSON string.
public function toJson(int $options = 0): string
JSON encoding options (same as json_encode()).
$json = $xmlObject->toJson();
$prettyJson = $xmlObject->toJson(JSON_PRETTY_PRINT);
jsonSerialize()
Prepare the object for JSON serialization.
public function jsonSerialize(): array
Returns an array representation suitable for JSON encoding.
$data = json_encode($xmlObject);
Array Conversion
toArray()
Convert the object to a plain PHP array.
public function toArray(): array
Returns the object as a plain array with nested conversions.
$array = $xmlObject->toArray();
The toArray() method recursively converts nested XMLObject instances to arrays.
Complete Examples
Working with XMLElement
use Flowgistics\XML\Facades\XML;
// Sample XML
$xmlString = '<?xml version="1.0"?>
<users>
<user id="1" role="admin">
<name>John Doe</name>
<email>[email protected]</email>
</user>
<user id="2" role="user">
<name>Jane Smith</name>
<email>[email protected]</email>
</user>
</users>';
file_put_contents('users.xml', $xmlString);
// Import as raw XMLElement
$xml = XML::import('users.xml', true);
// Iterate and access attributes
foreach ($xml->user as $user) {
$id = $user->attribute('id');
$role = $user->attribute('role', 'guest');
$name = (string) $user->name;
$email = (string) $user->email;
echo "User #$id: $name ($role) - $email\n";
// Check for optional attributes
if ($user->hasAttribute('verified')) {
$verified = $user->attribute('verified');
echo "Verified: $verified\n";
}
}
Working with XMLObject
use Flowgistics\XML\Facades\XML;
// Import XML (returns XMLCollection, which contains XMLObject)
$collection = XML::import('users.xml');
$data = $collection->get();
// Access as object properties
echo $data->user->name;
// Access as array
echo $data['user']['email'];
// Modify data
$data->user->status = 'active';
$data['user']['last_login'] = now();
// Check existence
if (isset($data->user)) {
// User exists
}
// Count items
echo "Total items: " . count($data);
// Iterate
foreach ($data as $key => $value) {
echo "$key: " . print_r($value, true);
}
// Convert to JSON
$json = $data->toJson(JSON_PRETTY_PRINT);
// Convert to array
$array = $data->toArray();
// Access attributes
$userId = $data->attribute('id');
if ($data->hasAttribute('version')) {
$version = $data->attribute('version');
}
Key Differences
| Feature | XMLElement | XMLObject |
|---|
| Extends | SimpleXMLElement | None |
| Raw XML | Yes | No |
| Processed Data | No | Yes |
| Array Access | Limited | Full |
| Modification | Limited | Full |
| Best For | Reading XML structure | Working with data |
Use XMLElement when you need to work with the raw XML structure. Use XMLObject when you need to manipulate the data as arrays or objects.