开发者

Getting value from SimpleXMLElement Object

开发者 https://www.devze.com 2023-03-28 19:27 出处:网络
Hi I have this following segment of XML: ...... <Result number=\"4\" position=\"1\" points=\"25\">

Hi I have this following segment of XML:

......
            <Result number="4" position="1" points="25">
                <Driver driverId="button" ur开发者_运维技巧l="http://en.wikipedia.org/wiki/Jenson_Button">
                    <GivenName>Jenson</GivenName>
                    <FamilyName>Button</FamilyName>
                    <DateOfBirth>1980-01-19</DateOfBirth>
                    <Nationality>British</Nationality>
                </Driver>
......

I can use the following easily to get the GivenName:

$item->Driver->GivenName;

But when I use:

$item->Driver->FamilyName;

I get SimpleXMLElement Object ()

I have looked around and found that it might be something to do with passing it to a string but then I get nothing on screen. Not even SimpleXMLElement Object.

I don't understand as it's a sibling of GivenName and that works.


You get a SimpleXMLElement object in both cases, which you'll see if you use print_r():

print_r ($item->Driver->GivenName);
print_r ($item->Driver->FamilyName);

Outputs:

SimpleXMLElement Object
(
    [0] => Jenson
)
SimpleXMLElement Object
(
    [0] => Button
)

You can use an explicit cast to get the values as strings:

$givenNameString = (string) $item->Driver->GivenName;
$familyNameString = (string) $item->Driver->FamilyName;


To make PHP understand you have to give typecasting forcefully on object like below:

$givenName = (array) $item->Driver->GivenName; 
$familyName = (array) $item->Driver->FamilyName;

print_r($givenName);
print_r($familyName);

OUTPUT :

Array ([0] => 'Jenson')
Array ([0] => 'Button')
0

精彩评论

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

关注公众号