Need help to solve my issue with XML!

Hello and Happy New Year everyone!!!

Need help to solve my issue with XML!

Here is my code:

$xml = new SimpleXMLElement('<xml/>');
$query = mysqli_query($conn, "
		SELECT * FROM timesheets WHERE period_code='2018_11_0'
		AND person_code='001899'
		GROUP BY period_code, person_code, object_id
") or die (mysqli_error($conn));

while($row = mysqli_fetch_assoc($query)){

    $data = $xml->addChild('data');
	$data->addChild('period_code', $row['period_code']);

	$person = $data->addChild('person');
	$person->addChild('person_code', $row['person_code']);
	$object = $person->addChild('object');
	$object->addChild('object_id', $row['object_id']);

}

Header('Content-type: text/xml');
print($xml->asXML());

This is XML i get:

<xml>
	<data>
		<period_code>2018_11_0</period_code>
		<person>
			<person_code>001899</person_code>
			<object>
				<object_id>LIG693</object_id>
			</object>
		</person>
	</data>
	<data>
		<period_code>2018_11_0</period_code>
		<person>
			<person_code>001899</person_code>
			<object>
				<object_id>LIG695</object_id>
			</object>
		</person>
	</data>
</xml>

This is XML i m after:

<xml>
	<data>
		<period_code>2018_11_0</period_code>
		<person>
			<person_code>001899</person_code>
			<object>
				<object_id>LIG693</object_id>
			</object>
			<object>
				<object_id>LIG695</object_id>
			</object>			
		</person>
	</data>
</xml>

So at end it should give out unique period code only once and inside each unique person_code and each unique object_if for each person! What am i doing wrong?

Thanks!

It seems to me that your loop adds a new child for period_code and person_code regardless of whether that data has changed since the last iteration. Obviously in this test code neither of those values change, but presumably the code will later be used for multiples of each of those values, I’d imagine you need to maintain a “last value” for each of them, and when it changes, close the previous nodes to get back “up” to the appropriate level in the XML.

(I haven’t done much with writing XML and may have just demonstrated that above).

1 Like

Hmm i still need to test that allot but for now it seems to be working! Thanks for now!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.