Alexa Adrian
Alexa Adrian

Reputation: 1858

How to loop through a SimpleXMLElement object in Php?

How to loop through a SimpleXMLElement object? This is what I have: I tried in many ways to iterate, but no success:

SimpleXMLElement Object
(
    [products] => SimpleXMLElement Object
        (
            [product] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [product_name] => PROD1
                            [price] => 100.2
                            [has_special_price] => true
                            [special_price_desc] => DESC SPECIAL PRICE
                            [id_product_remote] => CUSTOMID-01
                            [decimals] => 0
                            [category_key] => 1
                            [packaging_key] => 2
                            [stock_type_key] => 1
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [product_name] => PROD2
                            [price] => 200.2
                            [has_special_price] => false
                            [special_price_desc] => DEsdSC SPECIAL PRICE
                            [id_product_remote] => CUSTOMID-02
                            [decimals] => 0
                            [category_key] => 1
                            [packaging_key] => 2
                            [stock_type_key] => 1
                        )

                )

        )

    [products_client] => SimpleXMLElement Object
        (
            [product_client] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [id_client_remote] => CUSTOMCLIENT-01
                            [id_product_remote] => CUSTOMID-01
                            [custom_price] => 0
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [id_client_remote] => CUSTOMCLIENT-02
                            [id_product_remote] => CUSTOMID-02
                            [custom_price] => 1
                        )

                )

        )

)

Upvotes: 0

Views: 1313

Answers (2)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Try doing:


foreach($yourVar->products->product as $key => $val) {
   echo $val->product_name; /// and so on
}

Upvotes: 1

472084
472084

Reputation: 17885

What have you tried?

foreach($xml_object->products->product as $key => $product){
    echo $product->product_name;
}

Upvotes: 4

Related Questions