M Praus
M Praus

Reputation: 11

How to get contents of child tag of a parent tag in xml using php

I'm trying to get the content of a tag that is within another tag together with a specifig ID tag. The source is the below xml response:

The Xml response is here

<PricePlans>
    <PricePlan>
        <Description>Check Email</Description>
        <ID>1</ID>
        <Price>2</Price>
        <Time>900</Time>
    </PricePlan>
    <PricePlan>
        <Description>High Speed</Description>
        <ID>2</ID>
        <Price>5</Price>
        <Time>3600</Time>
    </PricePlan>
</PricePlans>

my php code is here:

echo "Desc" ." ".$xml->PricePlan->Description ."</br>";

This code gives me the content of the first "Description" tag (Check Email) but I want the description of a priceplan with a specifig "ID" tag (e.g. ID 2 - "High Speed") The xml response might have even more "PricePlan" tags but each has a unique value in the "ID" tag.

Upvotes: 1

Views: 143

Answers (2)

nanocv
nanocv

Reputation: 2229

To take the Description of an element with a particular ID you can use xpath.

$id = 2;

// xpath method always returns an array even when it matches only one element,
// so if ID is unique you can always take the 0 element
$description = $xml->xpath("/PricePlans/PricePlan/ID[text()='$id']/../Description")[0];

echo $description; // this echoes "High Speed"

Upvotes: 1

Goodnickoff
Goodnickoff

Reputation: 2267

You can access them the same as array:

echo($xml->PricePlan[0]->Description);
//Check Email
echo($xml->PricePlan[1]->Description);
//High Speed

foreach ($xml->PricePlan as $pricePlan) {
    echo($pricePlan->Description);
}
//Check Email
//High Speed

If you need to find element by value in ID you may use xpath:

$el = $xml->xpath('/PricePlans/PricePlan/ID[text()=2]/..');

Upvotes: 1

Related Questions