SBB
SBB

Reputation: 8990

PHP Find Value in Simple XML Object

I have a PHP Simple XML Object with multiple values in it.

I am trying to target a specific QID in the object and find out the corresponding Role is.

Example:

SimpleXMLElement Object
(
    [data] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [QID] => Q5678
                    [Role] => Super Admin
                )

            [1] => SimpleXMLElement Object
                (
                    [QID] => Q1234
                    [Role] => Super Admin
                )

        )

)

I couldn't really find anything that allowed me to search an object in this fashion like I can in JavaScript.

Would there be a way to say (Psuedo Code) : getRole('Q1234'); // Output Super Admin

I am able to change the structure of this output if needed but more so looking for verification that I can find this "Needle in a haystack" so to speak.

Upvotes: 0

Views: 1433

Answers (2)

ThW
ThW

Reputation: 19512

Use Xpath. It is an expression language that allows you to fetch parts of an DOM using location paths (including conditions). In SimpleXML that feature is limited, SimpleXMLElement::xpath() will always return an array of SimpleXMLElement objects.

$xml = <<<'XML'
<roles>
  <data>
    <QID>Q5678</QID>
    <Role>Super Admin</Role>
  </data>
  <data>
    <QID>Q1234</QID>
    <Role>Standard User</Role>
  </data>
</roles>
XML;

$roles = new SimpleXMLElement($xml);

var_dump(
  (string)$roles->xpath('//data[QID="Q1234"]/Role')[0]
);

Output:

string(13) "Standard User"

The expression //data fetches any data element node in the document. [QID="Q1234"] is an condition that limits the result to elements with an QID child node with the content Q1234. Adding /Role fetches the Role child nodes of that filtered node list.

The result is an array of SimpleXMLElement objects, so you need to fetch the first element of the array and cast it into a string.

In DOM you could fetch the string directly:

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);


var_dump(
  $xpath->evaluate('string(//data[QID="Q1234"]/Role)')
);

Upvotes: 2

Asim Zaka
Asim Zaka

Reputation: 556

You have to use custom function. You can use function like as following

function find_role($object, $id) {
    foreach ($object->data as $inside_object) {
        if ($id == $inside_object->QID) {
           return $inside_object->Role;
        }
    }
return false;

}

It will return you role. You can print it as

echo find_role($object, "Q5678");

Upvotes: 1

Related Questions