使用PHP将文件附加到DomDocument

This is the XML structure that I need to re-build with DomDocument (PHP):

<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
    <d:prop>
        <d:getetag />
        <c:calendar-data />
    </d:prop>
    <c:filter>
        <c:comp-filter name="VCALENDAR" />
    </c:filter>
</c:calendar-query>

This is my code:

$doc  = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;

$query = $doc->createElement('c:calendar-query');
$query->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:c', 'urn:ietf:params:xml:ns:caldav');
$query->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:d', 'DAV:');

$prop = $doc->createElement('d:prop');
$prop->appendChild($doc->createElement('d:getetag'));
$prop->appendChild($doc->createElement('c:calendar-data'));

$filter = $doc->createElement('c:filter');
$filter->appendChild($doc->createElement('c:comp-filter'));

$query->appendChild($prop);
$query->appendChild($filter);
$doc->appendChild($query);
$body = $doc->saveXML();

How do I add <c:comp-filter name="VCALENDAR" /> to the DOM?

You've already got a <c:comp-filter/>, just use setAttribute() to give it the attribute.


Example:

$doc  = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;

$query = $doc->createElement('c:calendar-query');
$query->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:c', 'urn:ietf:params:xml:ns:caldav');
$query->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:d', 'DAV:');

$prop = $doc->createElement('d:prop');
$prop->appendChild($doc->createElement('d:getetag'));
$prop->appendChild($doc->createElement('c:calendar-data'));

$filter = $doc->createElement('c:filter');
$comp_filter = $doc->createElement('c:comp-filter');
$comp_filter->setAttribute('name', 'VCALENDAR');
$filter->appendChild($comp_filter);

$query->appendChild($prop);
$query->appendChild($filter);
$doc->appendChild($query);
$body = $doc->saveXML();

echo $body;

Output:

<c:calendar-query xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:d="DAV:">
  <d:prop>
    <d:getetag/>
    <c:calendar-data/>
  </d:prop>
  <c:filter>
    <c:comp-filter name="VCALENDAR"/>
  </c:filter>
</c:calendar-query>