0

I have the following code and I have been working to try to get this working.

<?php declare(strict_types=1);

$session_token = '?'; $xml = '';
$result = '<?xml version="1.0" encoding="utf-8"?>

<string xmlns="http://ws.careerbuilder.com/resumes/">&lt;Packet&gt;&lt;Errors /&gt;&lt;SessionToken&gt;3msk323msd-3312-CQ-2&lt;/SessionToken&gt;&lt;/Packet&gt;</string>
';

if ($result) {

    $xml = simplexml_load_string($result);
    print_r($xml);

    if ($xml !== false) {
        $session_token = $xml->SessionToken;
        echo PHP_EOL.'Session: '. $session_token;

    } else {
        echo 'Error: XML does NOT appear to be valid';
    }

} else
    echo 'Error: result does NOT appear be valid';

The problem is no matter what I'm not able to extract the <SessionToken> value from the XML. When I use print_r() I get the following:

SimpleXMLElement Object
(
    [0] => <Packet><Errors /><SessionToken>3msk323msd-3312-CQ-2</SessionToken></Packet>
)

2 Answers 2

2

Your input is entity-encoded. If this is really what it looks like, you'll need to decode it first:

$xml = simplexml_load_string(html_entity_decode($result));
$token = (string) $xml->Packet->SessionToken[0];
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry - this solution is wrong. You're merging the inner document (in the value) with its container using string operations.
2

You document contains nested XML. The text content of the string element is serialized XML. So you need to parse it after reading it.

$result = '<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://ws.careerbuilder.com/resumes/">&lt;Packet&gt;&lt;Errors /&gt;&lt;SessionToken&gt;3msk323msd-3312-CQ-2&lt;/SessionToken&gt;&lt;/Packet&gt;</string>
';

$string = new SimpleXMLElement($result);
$packet = new SimpleXMLElement((string)$string);
var_dump($packet);

Output:

object(SimpleXMLElement)#2 (2) {
  ["Errors"]=>
  object(SimpleXMLElement)#3 (0) {
  }
  ["SessionToken"]=>
  string(20) "3msk323msd-3312-CQ-2"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.