K
K
Konstantin2015-11-04 17:51:07
PHP
Konstantin, 2015-11-04 17:51:07

How to get parent tag attribute in xml documents using php?

There is an xml file with the following structure:

<catalog>
-<category id="1">
--<category id="2">
---<product id=1 name="Товар 1" />
---<product id=2 name="Товар 2" />
--</category>
-</category>
-<category id="3">
--<product id=3 name="Товар 3" />
-</category>
-</catalog>

To display a list of products, I use the following code:
$products= $catalog->getElementsByTagName("product");
echo "<table>";
echo "<tr><th>Id</th><th>Наименование</th></tr>";
foreach ($products as $product) {
    echo '<tr><td>'.$product->getAttribute('id') . '</td><td>'.$product->getAttribute('name') . '</td></tr>';
}
echo "</table>";
}

It is required to enter these goods into the database with binding to the category. Can you please tell me how to get (display in the rows of the table) the id of the category to which the product belongs?
For example, Product 1 and Product 2 belong to the category with id = 2, and Product 3 belongs to the category with id = 3.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Matrozov, 2015-11-04
@KoNnY

Probably: $product->parentNode->getAttribute('id') will return you the ID of the category taken from the tag above

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question