使用 PHP 将过滤器标签附加到 DomDocument


Append filtertag to DomDocument using PHP

这是我需要使用DomDocument(PHP)重新构建的XML结构:

<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>

这是我的代码:

$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();

如何将<c:comp-filter name="VCALENDAR" />添加到 DOM?

你已经有了一个<c:comp-filter/>,只需使用 setAttribute() 赋予它属性。


例:

$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;

输出:

<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>