jcadima
1/9/2017 - 4:16 AM

Reading XML with XMLReader

Reading XML with XMLReader

<?php

// members.xml
<members>
	<member id="1" position="president">
		<firstName>Jim</firstName>
		<lastName>Smith</lastName>
		<score>12</score>
	</member>
	<member id="2">
		<firstName>Hank</firstName>
		<lastName>Rogers</lastName>
		<score>18</score>
	</member>
	<member id="3" position="secretary">
		<firstName>Joy</firstName>
		<lastName>Ashton</lastName>
		<score>21</score>
	</member>
</members>




$xml = new XMLReader();
$xml->open('members.xml');
$members = array();
while($xml->read()) {

	//get member attributes
	if($xml->nodeType == XMLREADER::ELEMENT && $xml->localName == 'member') {
		$member = array();
		$member['id'] =  $xml->getAttribute('id');
		$member['position'] =  $xml->getAttribute('position');
	}

	//first name
	if($xml->nodeType == XMLREADER::ELEMENT && $xml->localName == 'firstName') {
		$xml->read();
		$member['firstName'] = $xml->value;
	}

	//last name
	if($xml->nodeType == XMLREADER::ELEMENT && $xml->localName == 'lastName') {
		$xml->read();
		$member['lastName'] = $xml->value;
	}

	//score
	if($xml->nodeType == XMLREADER::ELEMENT && $xml->localName == 'score') {
		$xml->read();
		$member['score'] = $xml->value;

		//since this is the last element, add the member array to the collection
		$members[] = $member;
	}
}


echo displayMembers($members);

function displayMembers($members) {

	$r = '';

	//show the members that were retrieved from the XML file
	if(count($members) > 0) {
		$r .= '<table>';
		foreach($members as $member) {
			$r .= '<tr>';
			$r .= '<td style="background-color:#eee; padding:3px">' . $member['id'] . '</td>';
			$r .= '<td style="background-color:#eee; padding:3px">' . $member['firstName'] . '</td>';
			$r .= '<td style="background-color:#eee; padding:3px">' . $member['lastName'] . '</td>';
			$r .= '<td style="background-color:#eee; padding:3px">' . $member['score'] . '</td>';
			$r .= '</tr>';
		}
		$r .= '</table>';
	}

	return $r;
}