StudioTime
StudioTime

Reputation: 23979

XML parsing only some nodes - PHP

I have the following example XML:

<PRODUCTRATINGLIST>
  <PRODUCT>
    <VENDORREF>AC308A~</VENDORREF>
    <RATING>100%</RATING>
    <REVIEWCOUNT>7</REVIEWCOUNT>
  </PRODUCT>
  <PRODUCT>
    <VENDORREF>AC308C~</VENDORREF>
    <RATING>98%</RATING>
    <REVIEWCOUNT>89</REVIEWCOUNT>
  </PRODUCT>
</PRODUCTRATINGLIST>

I'm simply trying to extract each node under PRODUCT:

$ratings = simplexml_load_file("test.xml");

foreach ($ratings->PRODUCT as $rating){
  $part = $rating->VENDORREF;
  $rating = str_replace('%','',$rating->RATING);
  $numReviews = $rating->REVIEWCOUNT;
}

If I then try to print each element e.g.

echo $part.' '.$rating.' '.$numReviews;

$numReviews is always blank and I have no idea why.

Upvotes: 0

Views: 28

Answers (2)

Mahadeva Prasad
Mahadeva Prasad

Reputation: 709

Check below code. You change the variable names.

$ratings = simplexml_load_file("test.xml");

foreach ($ratings->PRODUCT as $rating){
    $part = $rating->VENDORREF;
    $ratingVal = str_replace('%','',$rating->RATING);
    $numReviews = $rating->REVIEWCOUNT;
}

echo $part.' '.$ratingVal.' '.$numReviews;

Upvotes: 1

Jeroen de Jong
Jeroen de Jong

Reputation: 337

You are replacing the $rating array with a variable, fix it like this:

$part = $rating->VENDORREF;
$rating_string = str_replace('%','',$rating->RATING);
$numReviews = $rating->REVIEWCOUNT;

Upvotes: 1

Related Questions