benn_jgh Posted November 14, 2006 Share Posted November 14, 2006 I'm trying to create a XML parser that queries Amazon and gets back book information.Everything is running fine but I can't seem to access items that are nested (ie. the <URL> element)EG...<Item><Title> Book Title</Title><SmallImage> <URL> http://www.thisiswhatiwant.com </URL></SmallImage></Item>My PHP code is....$webserviceURL."&SubscriptionId=".$developerID."&Operation=ItemSearch&ResponseGroup=".$responseGroup."&AssociateTag=".$associateTag."&SearchIndex=".$searchIndex."&Keywords=".$keywords;$data = file_get_contents($url);$parser = xml_parser_create(); xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1); xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0); xml_parse_into_struct($parser, $data, $values, $index) or die("Error parsing XML file :("); for($i = 0; $i <= count($index['Item']); $i++) { echo "<br><br>"; foreach ($index as $key=>$val) { $var = $values[$val[$i]]['value']; switch($key) { case "ASIN": echo "ASIN: ".$var; break; case "Title": echo "Title: ".$var; break; case "Author": echo "Auhtor: ".$var; break; case "FormattedPrice": echo "Price: ".$var; break; case "DetailPageURL": echo "Page: <a href=\"".$var."\">view</a>"; break; case "SmallImage": echo "Image: ".$var; break; } } } Link to comment https://forums.phpfreaks.com/topic/27258-xml-help/ Share on other sites More sharing options...
Psycho Posted November 14, 2006 Share Posted November 14, 2006 That's because the URL value exists within the URL tags not the SmallImage tags. You could add URL to the case list, but that is not really correct because URL could exist as a subelement of other parent elements.Your parser will need to be able to account for multiple sub elements with the same name belonging to different parent elements. I use an array for each tag. If a new sub tag is opened I add that tag as a new element to the tags array. When a tag is closed I pop off the last one. Then during the processing I know that if the current tag = "URL" and the last tag = "SmallImage" then it is the value I am looking for. Link to comment https://forums.phpfreaks.com/topic/27258-xml-help/#findComment-124643 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.