开发者

Object creation from Xml Return and Modification

开发者 https://www.devze.com 2023-02-26 06:19 出处:网络
Let\'s say I have a Class (simplified): class User { public $firstName; public $lastName; public $address;

Let's say I have a Class (simplified):

class User
{
    public $firstName;
    public $lastName;
    public $address;
    public $city;
    public $state;
    public $zip;
    public $phoneNumber;
}

now let's say I have an XML return which looks like:

[User] => SimpleXM开发者_开发技巧LElement Object
       (
          [firstName] => foo
          [lastName] => bar              
          [address] => 3111 east 1
          [city] => oneVille
          [state] => Fo
          [zip] => 51155
          [phoneNumber] => 5551112222
        )

Is there an easy way to create a User object off that return so I could than modify the values? Assuming that the return ment to be fit my User class.

Thank you!


Roughly:

$userXml = new SimpleXMLElement($xml);
$userObj = new User();
foreach($userXml as $key => $value) {
    $userObj->$key = (string)$value;
}

I'm not sure I've got the iteration interface right, but that's close.


You could set up the constructor of your User class to accept an object of type SimpleXMLElement and use its value to populate your User; although if your user objects aren't doing anything other than holding the data, you've not really gained anything by having that class in the first place:

class User
{
    public $firstName;
    public $lastName;
    public $address;
    public $city;
    public $state;
    public $zip;
    public $phoneNumber;

    public function __construct( SimpleXMLElement $xml )
    {
        $this->firstName = isset( $xml->firstName ) ? $xml->firstName : '';
        ...
        $this->phoneNumber = isset( $xml->phoneNumber ) ? $xml->phoneNumber : '';
    }
}
$user = new User( $your_xml_element_object_here );

You could also use Frank's foreach loop to populate them dynamically, but presumably you would only want to assign those fields that already exist in your class definition.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号