Getting value from SimpleXMLElement Object

11,167

Solution 1

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;

Solution 2

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')
Share:
11,167
Cool Hand Luke
Author by

Cool Hand Luke

Updated on June 30, 2022

Comments

  • Cool Hand Luke
    Cool Hand Luke almost 2 years

    Hi I have this following segment of XML:

    ......
                <Result number="4" position="1" points="25">
                    <Driver driverId="button" url="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.