0

I have a sample object array as a variable $xmlobj

SimpleXMLElement Object(
[SearchId] => 10769920113727_1556288871357_170040
[Categories] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [total_subcategories] => 1
            )

        [SubCategory] => SimpleXMLElement Object
            (
                [Title] => Reproductor MP3 y Multimedia
                [Value] => 122701
                [NumberOfProducts] => 1
            )

    )

[Products] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [totalResultsAvailable] => 1
                [firstResultPosition] => 1
                [totalResultsReturned] => 1
                [currency] => EUR
                [totalMerchantsAvailable] => 1
                [searchOperator] => and
            )

        [Product] => SimpleXMLElement Object
            (
                [Offer] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [id] => f94af9ec5186b53051c9ccf083ebddec
                                [type] => MANUFACTURER_PRODUCTS
                            )

                        [Title] => Apple iPod Nano 6 8 GB Gris
                        [Description] => iPod Nano 6 8 GB - Gris
                        [LastModified] => 2019-04-26 01:10:56
                        [MobileFriendly] => false
                        [Merchant] => SimpleXMLElement Object
                            (
                                [@attributes] => Array
                                    (
                                        [id] => 15348713
                                    )

                                [Name] => Backmarket

                            )

                        [Price] => SimpleXMLElement Object
                            (
                                [@attributes] => Array
                                    (
                                        [currency] => EUR
                                    )

                                [Price] => 99.99
                                [DeliveryCost] => 19.9
                                [DeliveryCostDetails] => SimpleXMLElement Object
                                    (
                                        [DeliveryCost] => 19.9
                                    )

                                [TotalPrice] => 119.89
                                [PriceWithoutRebate] => 190
                                [Rebate] => 47
                            )

                        [ProductClass] => 2
                        [Availability] => 1
                        [DeliveryTime] => 24H / 4 días laborables
                        [Promo] => SimpleXMLElement Object
                            (
                            )

                        [OffensiveContent] => false
                        [FinancingOption] => SimpleXMLElement Object
                            (
                            )

                        [MerchantCategory] => Alta Tecnología  Imágenes y sonidos  Reproductor de MP3 Y MP4
                        [Brand] => Apple
                        [BrandId] => 211
                        [GreenProduct] => false
                    )

            )

    )

Now when I want to access e.g. price i do it like this:

$product_total_price = $xmlobj->Products->Product->Offer->Price->TotalPrice;

And it's OK - I get what I want, but I am having issue when I want "dynamically" to change what I am looking for like:

$search_part = "Products->Product->Offer->Price->TotalPrice";
$product_total_price = $xmlobj->$search_part;

I obviously get nothing... even when I try:

$product_total_price = $xmlobj."->".$search_part;

So my question is... how to do it ? :)

Thanks !

2
  • 1
    Why would you do that? It's not dynamic if you have to type "Products->Product->Offer->Price->TotalPrice" anyway. Maybe give more about how/why you want to do this. Commented Apr 26, 2019 at 14:43
  • I will have different searches through array and I want function to return search based on input... So search_part can be as well $search_part = Products->Product->Offer->Price->attributes()->currency; The point is that $search_part will be changed.... dynamically Anyway - is there a way to do it ? :) Commented Apr 26, 2019 at 14:46

2 Answers 2

2

You will have to construct the path by exploding into an array, then looping to get each property.

For example...

$searchPart = "Products->Product->Offer->Price->TotalPrice";
$searchPath = explode('->', $searchPart);

$current = $xmlobj;
foreach ($searchPath as $segment) {
    $current = $current->$segment;
}
var_dump($current);

or you can convert it to an array and then you will be able to get your attributes

$xml = simplexml_load_string($xmlobj);
$json = json_encode($xml);
$arr = json_decode($json,TRUE);

$parseString = 'Products->Product->Offer->Price->@attributes->currency';
$parsePath = explode('->', $parseString);

$current = $arr;
foreach ($parsePath as $segment) {
    $current = $current[$segment];
}
var_dump($current);
Sign up to request clarification or add additional context in comments.

3 Comments

It doesn't pick up this: $searchPart = "Products->Product->Offer->Price->attributes()->currency";
@Peter, I updated my answer with a second route so you can get your attributes.
Yap, Converting to regular array is the best option. Thanks !
0

You can take a look at eval that take your code as a string and evaluates it, but I strongly discourage its usage because it's a potentially (and very big) security hole.

Instead you could use explode passing as first argument -> and then loop over the resulting array to get the value you need:

$search_part = "Products->Product->Offer->Price->TotalPrice";
$chunks = explode("->", $search_part);

foreach ($chunks as $chunk) {
  $temp = $xmlobj[$chunk];
}

$product_total_price = $temp;

or something similar, and then you will get you price dynamically

Note that if $xmlObj is of type Object you will need to use $xmlObj->{$chunk} instead of $xmlobj[$chunk]

2 Comments

No the point is that whole "string" in variable $search_part will be changed externally... so it can be: $search_part = Products->Product->Offer->Price->attributes()->currency; or any other "path..."
This will work even in that case, it's enough to know what is the delimiter of the path

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.