在PHP字符串中嵌入PHP脚本

时间:2017-03-24 13:26:49

标签: php xml string foreach

您好我有从数据库中获取多个文件附件详细信息的代码,现在我必须在XML字符串中插入这些详细信息并用于进一步的代码

这是代码

<?php  
$FileAttachments = get_file_attachments();

$xml = '<soapenv:Envelope xmlns:soapenv="">
   <soapenv:Header>
      <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="" xmlns:wsu="">
         <wsu:Timestamp wsu:Id="TS-EB0B39D982F3D3DFE714897582537972">
            <wsu:Created>'.$created_date.'.797Z</wsu:Created>
         </wsu:Timestamp>
         <wsse:UsernameToken wsu:Id="UsernameToken-EB0B39D982F3D3DFE714897582496061">
            <wsse:Username>Testuser</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">Password*1</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </soapenv:Header>
   <soapenv:Body>
       <ns0:process xmlns:ns0="">
         <ns0:Incident>
            <ns2:FileAttachments>
               <ns2:FileAttachmentList>
                  <ns2:Data/>
                  <ns2:FileName>FileName</ns2:FileName>
                  <ns2:ID id="677"/>
                  <ns2:Description></ns2:Description>
               </ns2:FileAttachmentList>
            </ns2:FileAttachments>
         </ns0:Incident>
      </ns0:process>
   </soapenv:Body>
</soapenv:Envelope>' ;

echo $xml;
?>

函数get_file_attachments()返回文件ID,文件名和描述。我想在xml字符串中放一个循环,将这些字段嵌入到它中。

 <ns2:FileAttachments>
               <ns2:FileAttachmentList>
                  <ns2:Data/>
                  <ns2:FileName>FileName</ns2:FileName>
                  <ns2:ID id="677"/>
                  <ns2:Description></ns2:Description>
               </ns2:FileAttachmentList>
            </ns2:FileAttachments>

请帮忙。

1 个答案:

答案 0 :(得分:0)

您可以先遍历附件,然后将结果嵌入到xml中。 e.g:

$attachments = '';
for(...) {
    $attachments .= <<<END_XML
       <ns2:FileAttachments>
           <ns2:FileAttachmentList>
              <ns2:Data/>
              <ns2:FileName>$filename</ns2:FileName>
              <ns2:ID id="$id"/>
              <ns2:Description></ns2:Description>
           </ns2:FileAttachmentList>
        </ns2:FileAttachments>
END_XML;
}
$xml = '<soapenv:Envelope xmlns:soapenv="">
<soapenv:Header>
.....
       <ns0:process xmlns:ns0="">
         <ns0:Incident>
' . $attachments . '
         </ns0:Incident>
      </ns0:process>
   </soapenv:Body>
</soapenv:Envelope>' ;