Reputation: 67
I'm tried to parse XML response with DOM.
<GetBilletResult>
<sNomProduit>product 2</sNomProduit>
<sNomArticle>article 4</sNomArticle>
...
<tabGrilleHoraire>
<tabDetailTarifArticle>
<tabDetail>
<sDetail>Liste Pax : Pax n°1 [Âge:19]</sDetail>
<sAgePax>19;</sAgePax>
...
</tabDetail>
</tabDetailTarifArticle>
...
<tabGrilleHoraire>
</GetBilletResult>
I need to reorder the result and regroup the articles by products. The output should look like this :
sNomProduit : product 2
sNomArticle : article 1
tabGrilleHoraire
Working code (thanks to ConstantineUA) :
$processed = array();
foreach( $billets as $GetBilletResult )
{
$sNomProduit = $GetBilletResult->getElementsByTagName( "sNomProduit" )->item(0)->nodeValue;
$nIDProduit = $GetBilletResult->getElementsByTagName( "nIDProduit" )->item(0)->nodeValue;
$sNomArticle = $GetBilletResult->getElementsByTagName( "sNomArticle" )->item(0)->nodeValue;
$nIDArticle = $GetBilletResult->getElementsByTagName( "nIDArticle" )->item(0)->nodeValue;
$tabDetail = $GetBilletResult->getElementsByTagName( "tabDetail" );
if (!isset($processed[$sNomProduit])) {
$processed[$sNomProduit] = array();
}
$processed[$sNomProduit][] = array(
'nIDProduit' => $nIDProduit,
'sNomArticle' => $sNomArticle,
'nIDArticle' => $nIDArticle,
'tabDetail' => $tabDetail,
);
}
Loop:
foreach ($processed as $sNomProduit => $list) {
echo "<h3> ".$sNomProduit."</h3>";
foreach ($list as $item) {
echo "<h5> ".$item['sNomArticle'] . "</h5>";
foreach ($item['tabDetail'] as $node) {
var_dump ($node->nodeValue);
}
}
echo "<hr>";
}
Upvotes: 0
Views: 302
Reputation: 1051
I think you can get by with an additional associative array where you put all you nodes during the loop:
$processed = array();
foreach( $billets as $GetBilletResult )
{
$sNomProduit = $GetBilletResult->getElementsByTagName( "sNomProduit" )->item(0)->nodeValue;
$nIDProduit = $GetBilletResult->getElementsByTagName( "nIDProduit" )->item(0)->nodeValue;
$sNomArticle = $GetBilletResult->getElementsByTagName( "sNomArticle" )->item(0)->nodeValue;
$nIDArticle = $GetBilletResult->getElementsByTagName( "nIDArticle" )->item(0)->nodeValue;
if (!isset($processed[$sNomProduit])) {
$processed[$sNomProduit] = array();
}
$processed[$sNomProduit][] = array(
'nIDProduit' => $nIDProduit,
'sNomArticle' => $sNomArticle,
'nIDArticle' => $nIDArticle,
);
}
And then loop through this array to display results:
foreach ($processed as $sNomProduit => $list) {
echo "<b>sNomProduit : </b> ".$sNomProduit."<br>";
foreach ($list as $item) {
echo "<b>sNomArticle : </b> ".$item['sNomArticle'] . "<br>";
echo "<b>ListeTranche </b> ID_Tranche ".$item['nIDArticle'] . "<br>";
}
}
It looks that your xml isn't complete so please note that it's more like a pseudo-code rather than a complete solution.
Upvotes: 1