OVH Cloud OVH Cloud

probleme Xpath

1 réponse
Avatar
kalooni
Bonjour,

je débute actuellement dans le parsing XML sous PHP, et je me suis
arrêté sur XPath et la classe XPath.class.php qui permet de manipuler
facilement (?) cela.

Je récupère un fichier XML qui ressemble à çà

<ItemLookupResponse>
<Item>
...
<CustomerReviews>
<Review>
<Rating>4</Rating>
<Summary>Ceci est un titre</Summary>
...
</Review>
<Review>
<Rating>3</Rating>
<Summary>Ceci est un titre</Summary>
...
</Review>
<Review>
<Rating>2</Rating>
<Summary>Ceci est un titre</Summary>
...
</Review>
</CustomerReviews>
...
</Item>
</ItemLookupResponse>

Je souhaite donc enregistré les différentes info concernant les
Review(s).

je peux faire comme ceci:

require_once('include/XPath.class.php');
$xml = url de mon fichier XML;
$xpath->new XPath($xml);

$nodeCollection $xpath->match("/ItemLookupResonse/Item/CustomerReviews/Review/Rating");

$i = 0;
foreach ($nodeCollection as $node) {
$rating[$i++] = $xpath->getData($node);
}

$nodeCollection $xpath->match("/ItemLookupResonse/Item/CustomerReviews/Review/Summary");

$i = 0;
foreach ($nodeCollection as $node) {
$summary[$i++] = $xpath->getData($node);
}

et ainsi de suite pour tous les champs fils de mon noeud Review ... je
cherche donc une façon plus rapide et plus élégante de faire cela
mais je coince

voici comment je pensais faire

$xpath = new XPath($xml);
$node = $xpath->match("//CustomerReviews/Review/");

et à partir de là je ne sais pas comment faire pour récupérer les
fils ... relativement à $node. Une idée ? un exemple ?

Merci
Kalooni

1 réponse

Avatar
m-e-
"kalooni" a écrit dans le message de news:

[...]
voici comment je pensais faire

$xpath = new XPath($xml);
$node = $xpath->match("//CustomerReviews/Review/");

et à partir de là je ne sais pas comment faire pour récupérer
les
fils ... relativement à $node.
[...]


(si on parle bien de http://sourceforge.net/projects/phpxpath/)
Par ma compréhension de la documentation (voir notamment dans
l'introduction, la structure des tableaux décrivant des noeuds),
je suppose que ceci est une bonne piste :

<?php
$datasFromXml = array();
$xpath = new XPath($xml);
$nodeCollection = $xpath->match("//CustomerReviews/Review/");
foreach ($nodeCollection as $node) {
foreach ($node['childNodes'] as $childNode) {
$name = $childNode['name'];
if (! isset($datasFromXml[$name])) {
$datasFromXml[$name] = array();
}
$datasFromXml[$name][] =
$xpath->getData($childNode['xpath']);
}
}
?>

Cela vous aide-t-il ?