将xml输出添加到现有xml元素

时间:2016-12-19 08:53:20

标签: php xml

我正在尝试添加此Php文件的输出:

<?php

      include "dbcon.php";
      //include "GUID_Generator.php";
      //$caseID = $_REQUEST['caseID'];
      $caseID = "160000000091000002000000009101";
      $query_tb_prescript = "select doseUnit,frequency,medicineID,startDate, EndDate from tb_prescript where caseID = '$caseID'";
      $result_tb_prescript = mysql_query($query_tb_prescript) or die();
      while($row_tb_prescript = mysql_fetch_array($result_tb_prescript)){
      $doseUnit = $row_tb_prescript['doseUnit'];
      $frequency = $row_tb_prescript['frequency'];
      $medicineID = $row_tb_prescript['medicineID'];
      $startDate = $row_tb_prescript['startDate'];
      $EndDate = $row_tb_prescript['EndDate'];
    // GUID
    $first_code_tbcase = date("Ymd");
    $second_code_tbcase = mt_rand(1000, 9999);
    $third_code_tbcase = mt_rand(1000, 9999);
    $fourth_code_tbcase = mt_rand(1000, 9999);
    $fifth_code_tbcase = mt_rand(1000,9999).mt_rand(1000,9999).mt_rand(1000, 9999);
   $GUID = $first_code_tbcase.'-'.$second_code_tbcase.'-'.$third_code_tbcase.'-'.$fourth_code_tbcase.'-'.$fifth_code_tbcase;


   $query_medicine = "select name1,strength, strengthUnit from medicine where id = '$medicineID'";
      $result_medicine = mysql_query($query_medicine) or die();
      $row_medicine = mysql_fetch_array($result_medicine);
      $medicineName = $row_medicine['name1'];
      $medicinestrength = $row_medicine['strength'];
      $medicinestrengthUnit = $row_medicine['strengthUnit'];

$xml_medication = '<Medications>
  <Medication guid="'.$GUID.'" Medication="'.$medicineName.'" DoseUnit="'.$medicinestrengthUnit.'" DoseFrequency="'.$frequency.'" Dose="'.$medicinestrength .'" DateEnd="'.$EndDate.'" DateStart="'.$startDate.'">
    <Customattributes>
      <AttributeKey Archive="false" Name="Route"></AttributeKey>
      <AttributeKey Archive="false" Name="Days/week">'.$frequency.'</AttributeKey>
      <AttributeKey Archive="false" Name="Still On Medication"></AttributeKey>
      <AttributeKey Archive="false" Name="Indication"></AttributeKey>
      <AttributeKey Archive="false" Name="Type of Indication"></AttributeKey>
      <AttributeKey Archive="false" Name="Reason For Stopping"></AttributeKey>
      <AttributeKey Archive="false" Name="Occupation"></AttributeKey>
      <AttributeKey Archive="false" Name="Clinician action taken with regard to medicine if related to AE"></AttributeKey>
      <AttributeKey Archive="false" Name="Batch Number"></AttributeKey>
      <AttributeKey Archive="false" Name="EFFECT OF DECHALLENGE (D) &amp; RECHALLENGE (R)"></AttributeKey>
    </Customattributes>
  </Medication>
</Medications>';


  echo $xml_medication;

}

?>

到这个文件的输出。(SAMPLE2.php)

  <?php

     include "dbcon.php";
     //$caseID = $_REQUEST['caseID'];
     //include "queries.php";
     //include "medicationsloop3.php";
     error_reporting('0'); 
     ini_set('display_errors', 1);
     // Generate GUIDs -------------------------------------------------------------

// GUID for TB Case
$query_guid_tbcase = "select * from `interop_id` where caseID = '$caseID'";
$result_guid_tbcase = mysql_query($query_guid_tbcase) or die();
$total_guid_tbcase = mysql_num_rows($result_guid_tbcase);
$row_guid_tbcase = mysql_fetch_array($result_guid_tbcase);

  if($total_guid_tbcase == 0){
    // GUID
    $first_code_tbcase = date("Ymd");
    $second_code_tbcase = mt_rand(1000, 9999);
    $third_code_tbcase = mt_rand(1000, 9999);
    $fourth_code_tbcase = mt_rand(1000, 9999);
    $fifth_code_tbcase = mt_rand(1000, 9999).mt_rand(1000, 9999).mt_rand(1000, 9999);
    $guid_code_tbcase = $first_code_tbcase.'-'.$second_code_tbcase.'-'.$third_code_tbcase.'-'.$fourth_code_tbcase.'-'.$fifth_code_tbcase;
  }else{
    $guid_code_tbcase = $row_guid_tbcase['GUID'];
  }

$subscriber = 'PH-ITIS-001';
$xml_payload = '<Patients>
<Patient guid="20161208-9093-4438-8722-714450479963" FirstName ="RANCE" Surname = "REMEDIO" MiddleName = "RANA" CreatedDate = "2016-12-08 08:48:20" LastUpdated = "2016-12-08 08:48:20" DateOfBirth="1987-03-08" Facility="09 - Sorsogon Medical Mission Group Hospital" Archive="false">
<Customattributes>
<AttributeKey Archive="false" Name="Medical Record Number">DR-TB0000002</AttributeKey>
<AttributeKey Archive="false" Name="Patient Identity Number">16000000009</AttributeKey>
<AttributeKey Archive="false" Name="Identity Type">9MTR Study</AttributeKey>
 <AttributeKey Archive="false" Name="Gender">Male</AttributeKey>
 <AttributeKey Archive="false" Name="MaritalStatus">MARRIED</AttributeKey>
 <AttributeKey Archive="false" Name="Employment Status">Employed</AttributeKey>
  <AttributeKey Archive="false" Name="Occupation">PROGRAMMER</AttributeKey>
 <AttributeKey Archive="false" Name="Language"></AttributeKey>
 <AttributeKey Archive="false" Name="Address">1241 MACARIO SACAY STREET</AttributeKey>
  <AttributeKey Archive="false" Name="Address Line 2">MAKATI CITY</AttributeKey>
  <AttributeKey Archive="false" Name="City">MAKATI CITY</AttributeKey>
  <AttributeKey Archive="false" Name="State"></AttributeKey>
  <AttributeKey Archive="false" Name="Postal Code">1232</AttributeKey>
  <AttributeKey Archive="false" Name="Patient Contact Number">+639973771272</AttributeKey>
  <AttributeKey Archive="false" Name="Country of Birth">Philippines</AttributeKey>
   <AttributeKey Archive="false" Name="Medical Record Number Type">DR-TB</AttributeKey>
 </Customattributes>
 <the medication tag will be put here!!!!>
 <LabTests>
 <LabTest guid="a0002d35-a804-fe4b-e943-abc2300040F4" LabValue="1" TestUnit="" LabTest="Chest X-Ray" TestResult="Positive" TestDate="2016-03-04">
  <Customattributes>
     <AttributeKey Archive="false" Name="Remarks">Chest X-Ray results are in</AttributeKey>
  </Customattributes>
  </LabTest>
  </LabTests>
  <Conditions>
  <Condition guid="b4ccd4a3-2354-6456-a4c3-abc04e0002Be" DateEnd="2016-10-04" DateStart="2016-01-04" TreatmentStartDate="2016-03-04" Terminology="10019805">
   <Customattributes>
   <AttributeKey Archive="false" Name="Condition Ongoing"></AttributeKey>
   </Customattributes>
   </Condition>
   </Conditions>
   <ClinicalEvents>
       <ClinicalEvent guid="b4ccd4a3-2354-5678-1234-abc04e00045f" SourceDescription="Headache" SourceTerminology="10019805" ResolutionDate="2016-10-04" OnsetDate="2016-04-04">
         <Customattributes>
           <AttributeKey Archive="false" Name="Outcome">Resolving</AttributeKey>
           <AttributeKey Archive="false" Name="Intensity (Severity)">Moderate</AttributeKey>
           <AttributeKey Archive="false" Name="Severity Grading Scale">WHO Scale</AttributeKey>
           <AttributeKey Archive="false" Name="Severity Grade">Grade 1</AttributeKey>
           <AttributeKey Archive="false" Name="Is the adverse event serious?">Yes</AttributeKey>
           <AttributeKey Archive="false" Name="Seriousness"></AttributeKey>
           <AttributeKey Archive="false" Name="Admission Date">2016-09-04</AttributeKey>
           <AttributeKey Archive="false" Name="Discharge Date"></AttributeKey>
           <AttributeKey Archive="false" Name="Date of Death"></AttributeKey>
           <AttributeKey Archive="false" Name="Autopsy Done"></AttributeKey>
           <AttributeKey Archive="false" Name="Was the AE attributed to one or more drugs?">Yes</AttributeKey>
           <AttributeKey Archive="false" Name="Was the event reported to national PV?">Yes</AttributeKey>
           <AttributeKey Archive="false" Name="Full Name of Reporter"></AttributeKey>
          <AttributeKey Archive="false" Name="Date of Report">2016-09-22</AttributeKey>
          <AttributeKey Archive="false" Name="Outcome"></AttributeKey>
          <AttributeKey Archive="false" Name="Type of Reporter">Other health professional</AttributeKey>
          <AttributeKey Archive="false" Name="Reporter Contact Number">9876543456</AttributeKey>
          <AttributeKey Archive="false" Name="Expected or Unexpected AE">         </AttributeKey>
          <AttributeKey Archive="false" Name="Treatment of Reaction">No Treatment</AttributeKe y>
       </Customattributes>
     </ClinicalEvent>
   </ClinicalEvents>
       <Encounters>
        <Encounter guid="1111be4a-eebb-bb3e-a4c3-a4d14e12344f" EncounterType="Pre-Treatment Visit" EncounterDate="2016-04-04">
        <InstanceValues>
        <InstanceValue Archive="false" ElementName="Weight (kg)">67</InstanceValue>
        <InstanceValue Archive="false" ElementName="Height (cm)">172</InstanceValue>
        <InstanceValue Archive="false" ElementName="Indication for Treatment (TB)">Pulmonary TB</InstanceValue>
        <InstanceValue Archive="false" ElementName="Previous TB treatment?">Yes</InstanceValue>
        <InstanceValue Archive="false" ElementName="Pregnancy Status">NA</InstanceValue>
        <InstanceValue Archive="false" ElementName="Date of last menstrual period">NA</InstanceValue>
        <InstanceValue Archive="false" ElementName="Estimated gestation (weeks)"></InstanceValue>
        <InstanceValue Archive="false" ElementName="Breastfeeding mother"></InstanceValue>
        <InstanceValue Archive="false" ElementName="Site of TB"></InstanceValue>
        <InstanceValue Archive="false" ElementName="Injecting Drug Use Within Past Year"></InstanceValue>
         <InstanceValue Archive="false" ElementName="Excessive alcohol use within the past year"></InstanceValue>
       <InstanceValue Archive="false" ElementName="Tobacco use within the past year"></InstanceValue>
      <InstanceValue Archive="false" ElementName="Documented HIV infection"></InstanceValue>
      <InstanceValue Archive="false" ElementName="Baseline Chest Xray Presentation"></InstanceValue>
      <InstanceValue Archive="false" ElementName="Ever received treatment with first line anti-TB drugs for &gt;-1 month prior to this episode?"> </InstanceValue>
      <InstanceValue Archive="false" ElementName="Ever received treatment with second line anti-TB drugs for &gt;-1 month prior to this episode?"> </InstanceValue>
      <InstanceValue Archive="false" ElementName="Isoniazid susceptibility by any laboratory test(s)">Susceptible</InstanceValue>
      <InstanceValue Archive="false" ElementName="Isoniazid confirmation">Xpert</InstanceValue>
      <InstanceValue Archive="false" ElementName="Rifampicin susceptibility by any laboratory test(s)"> </InstanceValue>
      <InstanceValue Archive="false" ElementName="Rifampicin confirmation"> </InstanceValue>
     </InstanceValues>
      </Encounter>
     </Encounters>
     </Patient>
     </Patients>';  

 $xml_body = '<?xml version="1.0" encoding="utf-8"?>
      <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
          <soap:Body>
            <Interop_Push xmlns="http://sample.org/webservices/">
               <subscriber>'.$subscriber.'</subscriber>
                <payload>
                  <![CDATA['.$xml_payload.']]>    
                </payload>
            </Interop_Push>
          </soap:Body>
      </soap:Envelope>';     


        echo $xml_body;

     $header = array(
          "POST: /webservice/InteropGeneric.asmx HTTP/1.1",
          "Host: example.net",
          "Content-Type: text/xml; charset=utf-8",
          "Content-Length: ".strlen($xml_body),
          "SOAPAction: http://sample.org/webservices/Interop_Push"
          );  

    $url = 'http://example.net/webservice/InteropGeneric.asmx';

$ch = curl_init(); 
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE_PATH); 
  curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE_PATH); 
  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  curl_setopt($ch, CURLOPT_TIMEOUT, 300); 
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_body); 

  $result = curl_exec($ch);
  $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

  $doc = new DOMDocument();
  $doc->loadXML($result);
  $doc2 =  $doc->getElementsByTagName('Interop_PushResult')->item(0)->nodeValue;
  $response = $doc2;
  $reponse2 = array("Update completed successfully");
  $response3 = array("example.net");

  $newresponse = str_replace($reponse2, $response3, $response);

     echo $newresponse;

     die;

     curl_close($ch);

    ?>

我想要做的是将sample1.php的输出(在源代码上查看时的Xml文件结构)显示到sample2.php的输出(在源代码上查看时的Xml文件结构)。这样我就可以获得患者信息的完整xml文件。

请帮忙!

1 个答案:

答案 0 :(得分:0)

考虑在两个脚本中将两个XML文件转储到磁盘,以后可以删除:

file_put_contents('Patients.xml', $xml_payload);

file_put_contents('Medications.xml', $xml_medication);

然后将两者合并为XSLT,这是一个用于处理XML文档的声明性专用语言。 PHP有一个内置的XSLT 1.0处理器libxslt,您必须通过取消注释php_xsl项来启用.ini。具体来说,XSLT具有document()功能,允许它从外部文件中检索节点。要正常工作,文件应位于同一目录中。 XSLT还很漂亮!

XSLT 脚本(外部保存为.xsl文件)

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
 <xsl:output version="1.0" encoding="UTF-8" indent="yes" />
 <xsl:strip-space elements="*"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Patient">
   <xsl:copy>
     <xsl:apply-templates select="@*"/>
     <xsl:copy-of select="Customattributes"/>
     <xsl:copy-of select="document('Medications.xml')/Medication"/>
     <xsl:apply-templates select="node()[name()!='Customattributes']"/>
   </xsl:copy>
  </xsl:template>  

</xsl:transform>

PHP 脚本(注意以下仅在上面的XSLT中引用Medications.xml)

// LOAD XML 
$dom = new DOMDocument();
$dom->load('Patients.xml');

// LOAD XSL
$xsl = new DOMDocument();
$xsl->load('XSLTScript.xsl');

// INITIALIZE TRANSFORMER
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); 

// TRANSFORM XML
$newXML = $proc->transformToXML($dom);

// SAVE FILE    
file_put_contents('Output.xml', $newXML);

// DELETE SOURCE FILES
unlink('Patients.xml')
unlink('Medications.xml')

<强>输出

<?xml version="1.0" encoding="UTF-8"?>
<Patients>
  <Patient guid="20161208-9093-4438-8722-714450479963" FirstName="RANCE" Surname="REMEDIO" MiddleName="RANA" CreatedDate="2016-12-08 08:48:20" LastUpdated="2016-12-08 08:48:20" DateOfBirth="1987-03-08" Facility="09 - Sorsogon Medical Mission Group Hospital" Archive="false">
    <Customattributes>
      <AttributeKey Archive="false" Name="Medical Record Number">DR-TB0000002</AttributeKey>
      <AttributeKey Archive="false" Name="Patient Identity Number">16000000009</AttributeKey>
      <AttributeKey Archive="false" Name="Identity Type">9MTR Study</AttributeKey>
      <AttributeKey Archive="false" Name="Gender">Male</AttributeKey>
      <AttributeKey Archive="false" Name="MaritalStatus">MARRIED</AttributeKey>
      <AttributeKey Archive="false" Name="Employment Status">Employed</AttributeKey>
      <AttributeKey Archive="false" Name="Occupation">PROGRAMMER</AttributeKey>
      <AttributeKey Archive="false" Name="Language"/>
      <AttributeKey Archive="false" Name="Address">1241 MACARIO SACAY STREET</AttributeKey>
      <AttributeKey Archive="false" Name="Address Line 2">MAKATI CITY</AttributeKey>
      <AttributeKey Archive="false" Name="City">MAKATI CITY</AttributeKey>
      <AttributeKey Archive="false" Name="State"/>
      <AttributeKey Archive="false" Name="Postal Code">1232</AttributeKey>
      <AttributeKey Archive="false" Name="Patient Contact Number">+639973771272</AttributeKey>
      <AttributeKey Archive="false" Name="Country of Birth">Philippines</AttributeKey>
      <AttributeKey Archive="false" Name="Medical Record Number Type">DR-TB</AttributeKey>
    </Customattributes>
    <Medication guid="20161219-3747-9290-8909-957289965585" Medication="Kanamycin" DoseUnit="mg" DoseFrequency="7" Dose="500" DateEnd="2016-12-15" DateStart="2016-12-08">
      <Customattributes>
        <AttributeKey Archive="false" Name="Route"/>
        <AttributeKey Archive="false" Name="Days/week">7</AttributeKey>
        <AttributeKey Archive="false" Name="Still On Medication"/>
        <AttributeKey Archive="false" Name="Indication"/>
        <AttributeKey Archive="false" Name="Type of Indication"/>
        <AttributeKey Archive="false" Name="Reason For Stopping"/>
        <AttributeKey Archive="false" Name="Occupation"/>
        <AttributeKey Archive="false" Name="Clinician action taken with regard to medicine if related to AE"/>
        <AttributeKey Archive="false" Name="Batch Number"/>
        <AttributeKey Archive="false" Name="EFFECT OF DECHALLENGE (D) &amp; RECHALLENGE (R)"/>
      </Customattributes>
    </Medication>
    <LabTests>
      <LabTest guid="a0002d35-a804-fe4b-e943-abc2300040F4" LabValue="1" TestUnit="" LabTest="Chest X-Ray" TestResult="Positive" TestDate="2016-03-04">
        <Customattributes>
          <AttributeKey Archive="false" Name="Remarks">Chest X-Ray results are in</AttributeKey>
        </Customattributes>
      </LabTest>
    </LabTests>
    <Conditions>
      <Condition guid="b4ccd4a3-2354-6456-a4c3-abc04e0002Be" DateEnd="2016-10-04" DateStart="2016-01-04" TreatmentStartDate="2016-03-04" Terminology="10019805">
        <Customattributes>
          <AttributeKey Archive="false" Name="Condition Ongoing"/>
        </Customattributes>
      </Condition>
    </Conditions>
    <ClinicalEvents>
      <ClinicalEvent guid="b4ccd4a3-2354-5678-1234-abc04e00045f" SourceDescription="Headache" SourceTerminology="10019805" ResolutionDate="2016-10-04" OnsetDate="2016-04-04">
        <Customattributes>
          <AttributeKey Archive="false" Name="Outcome">Resolving</AttributeKey>
          <AttributeKey Archive="false" Name="Intensity (Severity)">Moderate</AttributeKey>
          <AttributeKey Archive="false" Name="Severity Grading Scale">WHO Scale</AttributeKey>
          <AttributeKey Archive="false" Name="Severity Grade">Grade 1</AttributeKey>
          <AttributeKey Archive="false" Name="Is the adverse event serious?">Yes</AttributeKey>
          <AttributeKey Archive="false" Name="Seriousness"/>
          <AttributeKey Archive="false" Name="Admission Date">2016-09-04</AttributeKey>
          <AttributeKey Archive="false" Name="Discharge Date"/>
          <AttributeKey Archive="false" Name="Date of Death"/>
          <AttributeKey Archive="false" Name="Autopsy Done"/>
          <AttributeKey Archive="false" Name="Was the AE attributed to one or more drugs?">Yes</AttributeKey>
          <AttributeKey Archive="false" Name="Was the event reported to national PV?">Yes</AttributeKey>
          <AttributeKey Archive="false" Name="Full Name of Reporter"/>
          <AttributeKey Archive="false" Name="Date of Report">2016-09-22</AttributeKey>
          <AttributeKey Archive="false" Name="Outcome"/>
          <AttributeKey Archive="false" Name="Type of Reporter">Other health professional</AttributeKey>
          <AttributeKey Archive="false" Name="Reporter Contact Number">9876543456</AttributeKey>
          <AttributeKey Archive="false" Name="Expected or Unexpected AE"/>
          <AttributeKey Archive="false" Name="Treatment of Reaction">No Treatment</AttributeKey>
        </Customattributes>
      </ClinicalEvent>
    </ClinicalEvents>
    <Encounters>
      <Encounter guid="1111be4a-eebb-bb3e-a4c3-a4d14e12344f" EncounterType="Pre-Treatment Visit" EncounterDate="2016-04-04">
        <InstanceValues>
          <InstanceValue Archive="false" ElementName="Weight (kg)">67</InstanceValue>
          <InstanceValue Archive="false" ElementName="Height (cm)">172</InstanceValue>
          <InstanceValue Archive="false" ElementName="Indication for Treatment (TB)">Pulmonary TB</InstanceValue>
          <InstanceValue Archive="false" ElementName="Previous TB treatment?">Yes</InstanceValue>
          <InstanceValue Archive="false" ElementName="Pregnancy Status">NA</InstanceValue>
          <InstanceValue Archive="false" ElementName="Date of last menstrual period">NA</InstanceValue>
          <InstanceValue Archive="false" ElementName="Estimated gestation (weeks)"/>
          <InstanceValue Archive="false" ElementName="Breastfeeding mother"/>
          <InstanceValue Archive="false" ElementName="Site of TB"/>
          <InstanceValue Archive="false" ElementName="Injecting Drug Use Within Past Year"/>
          <InstanceValue Archive="false" ElementName="Excessive alcohol use within the past year"/>
          <InstanceValue Archive="false" ElementName="Tobacco use within the past year"/>
          <InstanceValue Archive="false" ElementName="Documented HIV infection"/>
          <InstanceValue Archive="false" ElementName="Baseline Chest Xray Presentation"/>
          <InstanceValue Archive="false" ElementName="Ever received treatment with first line anti-TB drugs for &gt;-1 month prior to this episode?"/>
          <InstanceValue Archive="false" ElementName="Ever received treatment with second line anti-TB drugs for &gt;-1 month prior to this episode?"/>
          <InstanceValue Archive="false" ElementName="Isoniazid susceptibility by any laboratory test(s)">Susceptible</InstanceValue>
          <InstanceValue Archive="false" ElementName="Isoniazid confirmation">Xpert</InstanceValue>
          <InstanceValue Archive="false" ElementName="Rifampicin susceptibility by any laboratory test(s)"/>
          <InstanceValue Archive="false" ElementName="Rifampicin confirmation"/>
        </InstanceValues>
      </Encounter>
    </Encounters>
  </Patient>
</Patients>