PHP读取及生成xml文件实测

时间:2022-10-09 11:59:58

PHP生成xml文件方法的四个方法,博主google了下http://www.phppan.com/2009/10/use-php-create-xml-file/这篇写的还不错,实测用了php现成支持的DomDocument方式生成xml文件,是可以用的。

注意XMLWriter的方式生成需要PHP开启扩展php-xml支持。

以下是博主亲测可用的demo:

$xml = new DOMDocument('1.0', 'utf-8');
$xml_MeetingAttendee = $xml->createElement("MeetingAttendee");
$xml->appendChild($xml_MeetingAttendee);

$xml_PlanningCode = $xml->createElement("PlanningCode");
$xml_PlanningCode->nodeValue = 'FPLN891';
$xml_MeetingAttendee->appendChild( $xml_PlanningCode );

$xml_SendDate = $xml->createElement("SendDate");
$xml_SendDate->nodeValue = '2016-04-23 00:00:00';
$xml_MeetingAttendee->appendChild($xml_SendDate);

$xml_AttendeeList = $xml->createElement("AttendeeList");
$xml_MeetingAttendee->appendChild($xml_AttendeeList);
for($i = 0; $i < 2; $i++){
$xml_Attendee = $xml->createElement("Attendee");
$xml_AttendeeList->appendChild($xml_Attendee);

$xml_AttendeeType = $xml->createElement("AttendeeType");
$xml_AttendeeType->nodeValue = '1';
$xml_Attendee->appendChild($xml_AttendeeType);

$xml_AttendeeId = $xml->createElement("AttendeeId");
$xml_AttendeeId->nodeValue = '16705';
$xml_Attendee->appendChild($xml_AttendeeId);

$xml_AttendeeHCPID = $xml->createElement("AttendeeHCPID");
$xml_AttendeeHCPID->nodeValue = 'DR00080055';
$xml_Attendee->appendChild($xml_AttendeeHCPID);

$xml_AttendeeGUID = $xml->createElement("AttendeeGUID");
$xml_AttendeeGUID->nodeValue = 'DBCA2553-7CD0-E211-9BB8-005056985885';
$xml_Attendee->appendChild($xml_AttendeeGUID);

$xml_SignedTime = $xml->createElement("SignedTime");
$xml_SignedTime->nodeValue = '2016-04-23 00:00:00';
$xml_Attendee->appendChild($xml_SignedTime);
}

$xml->formatOutput=true;
$xml->save("meeting.xml");

 

生成后的xml文件结构:

<?xml version="1.0" encoding="utf-8"?>
<MeetingAttendee>
  <PlanningCode>FPLN891</PlanningCode>
  <SendDate>2016-04-23 00:00:00</SendDate>
  <AttendeeList>
    <Attendee>
      <AttendeeType>1</AttendeeType>
      <AttendeeId>16705</AttendeeId>
      <AttendeeHCPID>DR00080055</AttendeeHCPID>
      <AttendeeGUID>DBCA2553-7CD0-E211-9BB8-005056985885</AttendeeGUID>
      <SignedTime>2016-04-23 00:00:00</SignedTime>
    </Attendee>
    <Attendee>
      <AttendeeType>1</AttendeeType>
      <AttendeeId>16705</AttendeeId>
      <AttendeeHCPID>DR00080055</AttendeeHCPID>
      <AttendeeGUID>DBCA2553-7CD0-E211-9BB8-005056985885</AttendeeGUID>
      <SignedTime>2016-04-23 00:00:00</SignedTime>
    </Attendee>
  </AttendeeList>
</MeetingAttendee>

 

读取也有多种方法这里给出两种:

一、DOMDocument方式读取:

$doc = new DOMDocument(); 
$doc->load('test1.xml'); //读取xml文件 
$MeetingAttendee = $doc->getElementsByTagName( "MeetingAttendee" ); //取得标签的对象数组 
foreach( $MeetingAttendee as $row ) 
{ 
$PlanningCodes = $row->getElementsByTagName( "PlanningCode" ); //取得的标签的对象数组 
$PlanningCode = $PlanningCodes->item(0)->nodeValue; //取得标签中的值
echo $PlanningCode;
} 

二、SimpleXML方式读取

$xml_object = simplexml_load_file($localfile)
echo $xml_object->MeetingAttendee->PlanningCode;