This question already has answers here:
Answer
Solution:
You could use XPath to produce the individual items, something like
$country = $product->xpath("./properties/property[@name='country']/value")[0];
Or you could build a list of all of the properties as you loop over them and create an associative array...
foreach($xml->product as $index => $product) {
$details = [];
foreach ( $product->properties->property as $property ){
$details[(string)$property['name']] = (string)$property->value;
}
print_r($details);
which gives something like
Array
(
[country] => Spanje
[region] => Gran Canaria
[cityURL] => https://www.example.com/
[serviceType] => Logies ontbijt
)
The second method is (I think) more efficient as it does 1 pass over the data, XPath would have to be done for each element you need.
If you have multiples of some details...
foreach($xml->product as $index => $product) {
$details = [];
foreach ( $product->properties->property as $property ){
$type = (string)$property['name'];
$values = [];
foreach ( $property->value as $value ) {
$values[] = (string)$value;
}
if ( is_array($values) ) {
$details[$type] = $values;
}
else {
$details[$type] = $values[0];
}
}
print_r($details);
}
will give something like
Array
(
[country] => Array
(
[0] => Spanje
)
[region] => Array
(
[0] => Gran Canaria
)
[cityURL] => Array
(
[0] => https://www.example.com/
)
[usp] => Array
(
[0] => Adults only 16+
[1] => Een rustpunt op een centrale plek
[2] => Lichte kamers met ruimtelijke sfeer
)
[surrounding] => Array
(
[0] => afstand tot strand circa 1 kilometer (zandstrand)
[1] => afstand tot centrum: circa 1 kilometer
[2] => afstand tot Barstreet circa 500 meter
[3] => afstand tot luchthaven circa 30 kilometer
)
[serviceType] => Array
(
[0] => Logies ontbijt
)
)
Answer
Solution:
You can iterate over the property
details and see what you have. You also don't need the $xml->product
in the foreach
, that goes back to the parent.
$xml = new simplexmlelement($xml);
foreach($xml->product as $product) {
foreach($product->properties->property as $property) {
if($property['name'] == 'serviceType'){
echo 'Service type is' . $property->value . ' for ' . $product ->name;
}
}
}
Demo: https://3v4l.org/bQLUa
Answer
Solution:
I would something similar to the other answers, but using xpath:
$properties = $xml->xpath("//products//property");
foreach ($properties as $property) {
echo $property->attributes(). ": " . $property->value. "<br>";}
Output:
country: Spanje
region: Gran Canaria
cityURL: https://www.example.com/
serviceType: Logies ontbijt
roomType: 2-persoonskamer luxe type voor alleengebruik
roomOccupation: geschikt voor 1 persoon
roomType: 2-persoonskamer luxe type standaard
roomOccupation: geschikt voor 2 tot 3 personen
Source