Jump to content

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 
*/
 
Edited by us2rn4m2
Link to comment
https://forums.phpfreaks.com/topic/275073-xml-parse/#findComment-1415778
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.