aaantt Posted March 1, 2013 Share Posted March 1, 2013 the followings are XML sample code. Code XML: <m:ad xmlns:m="http://www.w3c.org/soap"><title><![CDATA[TITLE]]></title><phone>123456789</phone><attributeGroup><attribute id="14" name="A1">40</attribute><attribute id="15" name="A2">50</attribute></attributeGroup></m:ad> I only know PHP XMLReader to get value Code PHP: while ( $reader->read() ) {if ( $reader->nodeType ==XMLReader::ELEMENT && $reader->name == "attribute" ) {printf("id=%s, name=%s\n", $reader->getAttribute('id'), $reader->getAttribute('name'));}} But how to get attribute A1, A2 . I would like to get 40, and 50 both .Like thisid=14, name=A1, value 40id=15, name=A2, value 50 Thanks inadvanced Link to comment https://forums.phpfreaks.com/topic/275073-xml-parse/ Share on other sites More sharing options...
Christian F. Posted March 1, 2013 Share Posted March 1, 2013 The "40" and "50" are not attributes, they're the tags' content (or value). To find out how to get that, please see the SimpleXML examples in the PHP manual. Link to comment https://forums.phpfreaks.com/topic/275073-xml-parse/#findComment-1415769 Share on other sites More sharing options...
us2rn4m2 Posted March 1, 2013 Share Posted March 1, 2013 $xml = ' <m:ad xmlns:m="http://www.w3c.org/soap"> <title><![CDATA[TITLE]]></title> <phone>123456789</phone> <attributeGroup> <attribute id="14" name="A1">40</attribute> <attribute id="15" name="A2">50</attribute> </attributeGroup> </m:ad>'; $reader = new XMLReader(); $reader->xml($xml); $id = null; $name = null; while($reader->read() ) { if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == "attribute") { $id = $reader->getAttribute('id'); $name = $reader->getAttribute('name'); printf("id=%s, name=%s\n", $id, $name); } if(isset($id) && isset($name) && $reader->nodeType == XMLReader::TEXT) { printf("value = %s", $reader->value); echo '<br />'; } } /** Result: id=14, name=A1 value = 40 id=15, name=A2 value = 50 */ 2nd method $p = xml_parser_create(); xml_parse_into_struct($p, $xml, $values, $index); xml_parser_free($p); foreach($values as $v) { if(array_key_exists('attributes', $v)) { $attributes = $v['attributes']; if(array_key_exists('ID', $attributes) && array_key_exists('NAME', $attributes)) { echo 'id = ' . $attributes['ID'] . ', '; echo 'name = ' . $attributes['NAME'] . ', '; echo 'value ' . $v['value'] . ' <br />'; } } } /** Result id = 14, name = A1, value 40 id = 15, name = A2, value 50 */ Link to comment https://forums.phpfreaks.com/topic/275073-xml-parse/#findComment-1415778 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.