-3

I have XML in this format

<hotels>
    <hotel>
        <id>285</id>
        <name>Alexander</name>
        <price>250 USD</price>
    </hotel>

    <hotel>
        <id>678</id>
        <name>Hilton</name>
        <price>480 USD</price>
    </hotel>                
</hotels>

How do i get the name of hotel where id is 678 by using PHP?

Roi
  • 5
  • 2
  • 2
    Possible duplicate of [How do you parse and process HTML/XML in PHP?](https://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – Domso Dec 12 '18 at 08:58
  • @Domso - is the hotel tag was like this: `....` , would it was easier to get the NAME tag or do i still had to use FOREACH loop? – Roi Dec 12 '18 at 10:23

3 Answers3

1

Use simplexml_load_string() to parse xml string. Then loop through hotel tag and check content of id

$xml = simplexml_load_string($str);
foreach($xml->hotel as $hotel)
    $hotel->id == "678" ? @$name = (string)$hotel->name : '';
echo $name;

Check result in demo


Also you can use DOMXpath if you don't want to use foreach

$doc = new DOMDocument();
$doc->loadXML($str);
$name = (new DOMXpath($doc))->query("//hotel[id[text()='678']]/name")[0]->nodeValue;
// Hilton

Check result in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84
0

I hope this is what you're looking for :

$xmlstr = <<<XML
<hotels>
    <hotel>
        <id>285</id>
        <name>Alexander</name>
        <price>250 USD</price>
    </hotel>

    <hotel>
        <id>678</id>
        <name>Hilton</name>
        <price>480 USD</price>
    </hotel>                
</hotels>
XML;

$hotel = new SimpleXMLElement($xmlstr);
$list = $hotel->hotel;
$count = count($list);
while($count > 0){
    $count--;
    $id = $hotel->hotel[$count]->id;
    if($id == 678){
        $name = $hotel->hotel[$count]->name;
        echo $name;
    }
}
executable
  • 3,365
  • 6
  • 24
  • 52
  • Thank. Do i have to use WHILE loop and run on all the sections? is there any function that find section according some value? – Roi Dec 12 '18 at 10:10
0

You can use SimpleXML and XPath to find the hotel without using loops..

$data ='<hotels>
    <hotel>
        <id>285</id>
        <name>Alexander</name>
        <price>250 USD</price>
    </hotel>

    <hotel>
        <id>678</id>
        <name>Hilton</name>
        <price>480 USD</price>
    </hotel>
</hotels>';

$hotel = new SimpleXMLElement($data);
$hotel678 = $hotel->xpath("//hotel[id='678']");
echo $hotel678[0]->name;
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55