Jump to content

[SOLVED] SimpleXML Looping


RabPHP

Recommended Posts

Greetings,

 

Here is an issue I am running into.  I have an XML that looks like the following:

 

<Query>

    <Patient>

          <Study>

              <PatientID>1145566</PatientID>

              <StudyCode>x333333</StudyCode>

          </Study>         

          <Study>

              <PatientID>1145566</PatientID>

              <StudyCode>x222222</StudyCode>

          </Study>

      </Patient>

    <Patient>

          <Study>

              <PatientID>1145566</PatientID>

              <StudyCode>x4444444</StudyCode>

          </Study>

          <Study>

              <PatientID>1145566</PatientID>

              <StudyCode>x6666666</StudyCode>

          </Study>   

          <Study>

              <PatientID>1145566</PatientID>

              <StudyCode>x55555555</StudyCode>

          </Study>

      </Patient>

</Query>

 

My Code looks like the following:

 

$PAT_ID = '1145566';

 

  $xmlstring = file_get_contents("patients.xml");

  $xml = new SimpleXMLElement($xmlstring);

  foreach ($xml->Patient as $Patient) {

    if (strtolower($Patient->Study->PatientID) == "$PAT_ID") {

        $sid = $Patient->Study->StudyCode . "</p>";

        echo($sid);

    }

  }

 

When I do this, I only get the first StudyCode for each Patient.  I would like to get the StudyCodes for Each Study.  The PatientID in the file will always be the same, therefore I don't need that to actually be the qualifyier.  I just want to get the StudyCode for each Patient and set it as a variable.

 

I am really stumped, but know that I need to not just loop through patients but also loop through the Studies.  I am bad with nested loops, please advise if anyone can help.

 

Rab

Link to comment
https://forums.phpfreaks.com/topic/79483-solved-simplexml-looping/
Share on other sites

Seeing a visual representation of the data as an array (so you can see the indexes), the way php sees it, will probably help. See the following print_r() code added to your code and I believe the two foreach() loops that do what you want -

 

<?php
$PAT_ID = '1145566';

  $xmlstring = file_get_contents("patients.xml");
  $xml = new SimpleXMLElement($xmlstring);

echo "<pre>";
print_r($xml);
echo "</pre>";

foreach ($xml->Patient as $Patient)
{
foreach($Patient->Study as $Study)
{
	if (strtolower($Study->PatientID) == "$PAT_ID") {
		$sid = $Study->StudyCode . "</p>";
		echo($sid);
	}
}
}
?>

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.