Keith
Keith

Reputation: 26489

How to make an xpath result into a string with PHP?

if($xmlobj = simplexml_load_string(file_get_contents($xml_feed)))
{
    $result = $xmlobj->xpath("TrafficMeta");
}

The above code returns the desired result and when viewed with print_r it shows this, which is what I want to get (sessionId):

Array ( [0] => SimpleXMLElement Object ( [sessionId] => tbfm1t45xplzrongbtbdyfa5 ) ) 

How can I make this sessionId into a string?

Upvotes: 0

Views: 294

Answers (3)

soulmerge
soulmerge

Reputation: 75704

The function returns an array of SimpleXMLElement objects. To access the $sessionId member of the first array entry you do this:

echo $result[0]->sessionId;

Note that there might be more elements in the array, though. You should either assert that there is really exactly one or process all of them:

# either one of these
assert(count($result) === 1);
if (count($result) !== 1) throw new Exception('Unexpected data in xml');
# or this
foreach ($result as $object) {
    echo $object->sessionId;
}

Upvotes: 1

Gumbo
Gumbo

Reputation: 655189

Try $result[0]->sessionId.

Upvotes: 1

Lukáš Lalinský
Lukáš Lalinský

Reputation: 41306

I can't get it to work using XPath, but $result[0]['sessionId'] works fine. Use strval() on it if you need a real string.

Upvotes: 1

Related Questions