Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Created July 6, 2019 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/0e81751b616ddd625998e67d5c42feb2 to your computer and use it in GitHub Desktop.
Save mtvbrianking/0e81751b616ddd625998e67d5c42feb2 to your computer and use it in GitHub Desktop.
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