是否有类似“array_search”的函数用于simplexml对象

是否有类似“array_search”的函数用于simplexml对象

问题描述:

I have a codeigniter app that queryies an api and gets a simplexml object. I had hard coded the values I wanted from the simplexml object, but found out later that the structure of the object isn't always the same, so I can't use casting to get the values I need.

Is there an array_search like function that I could use for this so I can use the "classid" to get the value? Here is a sampling of the simplexml object:

    [Package] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [ID] => e981b9a72cd305c7d97cc530ef9b3015
            )

        [Postage] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [CLASSID] => 3
                            )

                        [MailService] => Express Mail<sup>&reg;</sup>
                        [Rate] => 57.60
                    )

                [1] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [CLASSID] => 2
                            )

                        [MailService] => Express Mail<sup>&reg;</sup> Hold For Pickup
                        [Rate] => 57.60
                    )

                [2] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [CLASSID] => 55
                            )

                        [MailService] => Express Mail<sup>&reg;</sup> Flat Rate Boxes
                        [Rate] => 39.95
                    )

I was using this to get the [Rate] value:

$usps->Package->Postage[0]->Rate

The problem is I need to use [CLASSID] because that is consistant where the data in the number key(?) changes.

Use XPath

You can not only search for specific elements, but do all kinds of crazy searches using various axes.

This should work, but I have no way of testing it without the raw XML:

$rates = array();

foreach ($usps->Package->Postage as $postage)
    $rates[$postage->attributes()->CLASSID] = $postage->Rate;