Created
July 6, 2019 14:46
-
-
Save mtvbrianking/0e81751b616ddd625998e67d5c42feb2 to your computer and use it in GitHub Desktop.
Custom xml element - with default value getter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'), | |
]); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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