Jump to content

XML parse


aaantt

Recommended Posts

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 this

id=14, name=A1, value 40
id=15, name=A2, value 50

 

Thanks inadvanced

Link to comment
https://forums.phpfreaks.com/topic/275073-xml-parse/
Share on other sites

$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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.