robinhood
robinhood

Reputation: 33

how to access xml tag by attribute of the parent

This is part of the xml:

<?xml version="1.0"?>
<menu>
 <pizzas>

<pizza number="0">
  <title>Tomato &amp; Cheese</title>
  <small>550</small>
  <medium></medium>
  <large>975</large>
</pizza>

PHP:

<?php
    session_start();
?>
<div id="basket">
    <h3 style="text-align:center; position:static;">Your Order:</h3>
    <?php
        $numberSelected = '';
        $_SESSION['link'] = $numberSelected;

        class dom{}

        $dom = new dom;
        $dom = simplexml_load_file("../../menu.xml");

        foreach ($dom->xpath("/menu/*/*") as $item)
        {
            print $item->title;
        }

        print_r($_SESSION);
    ?>
</div>

How can I print the title of the pizza/item using the number stored in the $numberSelected variable?

I somehow need to access the value inside the <title></title> tag, which is inside its parent e.g. <pizza number="x">, where x comes from the variable $numberSelected.

Upvotes: 1

Views: 35

Answers (1)

Kevin
Kevin

Reputation: 41885

You can just select the node where its attribute is using = thru xpath also:

[@number='$numberSelected']

So just query it and continue on getting the results if it did yielded. Use foreach if you're expecting more:

$result = $dom->xpath("//pizza[@number='$numberSelected']");
if(!empty($result)) {
    $pizza = $result[0];
    echo $pizza->title; // and others
}

Sample Output

Upvotes: 1

Related Questions