Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom xml element - with default value getter
<?php
$document = '
<document>
<users>
<id>1</id>
<salary>120</salary>
<is_admin>0</is_admin>
<invalid-key/>
<name>John Doe</name>
<email>jdoe@example.com</email>
<created_at>2018-07-12 17:06:13</created_at>
<updated_at></updated_at>
</users>
<users>
<id>2</id>
<salary>120</salary>
<is_admin></is_admin>
<invalid-key>Test</invalid-key>
<name>Gary Plant</name>
<email>gplant@example.com</email>
<created_at>2018-07-12 18:02:26</created_at>
<updated_at>2018-07-13 11:22:44</updated_at>
</users>
</document>';
$manifest = simplexml_load_string($document, XmlElement::class);
foreach($manifest->users as $user) {
print_r([
'id' => (int) $user->id,
'salary' => $user->get('salary', 0),
'is_admin' => (bool) $user->is_admin,
// 'invalid_key' => $user->{"invalid-key"},
'invalid_key' => $user->get('invalid-key'),
'name' => $user->name,
'email' => $user->email,
// 'created_at' => $user->created_at, // Default = ''
'created_at' => $user->get('created_at'), // Default = null
'updated_at' => $user->get('updated_at'),
]);
}
<?php
/**
* Custom XML element.
*/
class XMLElement extends \SimpleXMLElement
{
/**
* Provides access to element's children.
*
* With chance for default value.
*
* @param string $attr Attribute
* @param mixed $default Default Value
*
* @return mixed
*/
public function get($attr, $default = null)
{
if (empty($this->{$attr})) {
return $default;
}
return $this->{$attr};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.