在php中解析XML Caldav请求

时间:2014-06-25 08:51:00

标签: php xml caldav

我试图解析ThunderBird发送到我的CalDAV服务器的请求,以及从stackoverflow获取的示例,其中包含以下XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<products>
    <last_updated>2009-11-30 13:52:40</last_updated>
    <product>
        <element_1>foo</element_1>
        <element_2>foo</element_2>
        <element_3>foo</element_3>
        <element_4>foo</element_4>
    </product>
</products> 

使用该功能:

$XMLr = new XMLReader;
$XMLr->open('test.xml');

$doc = new DOMDocument;

// move to the first <product /> node
while ($XMLr->read() && $XMLr->name !== 'product');


// now that we're at the right depth, hop to the next <product/> until the end of the tree
    $node = simplexml_import_dom($doc->importNode($XMLr->expand(), true));

    // now you can use $node without going insane about parsing
    $children = $node->children();
    foreach($children as $child)
    {
        echo $child->getName();
        echo "\n";
    }

我得到答案&#34; element_1 element_2 element_3 element_4&#34;,但如果我在我的请求中使用相同的功能:

<?xml version="1.0" encoding="UTF-8"?>
<D:propfind xmlns:D="DAV:" xmlns:CS="http://calendarserver.org/ns/" xmlns:C="urn:ietf:params:xml:ns:caldav">
    <D:prop>
        <D:resourcetype/>
        <D:owner/>
        <D:current-user-principal/>
        <D:supported-report-set/>
        <C:supported-calendar-component-set/>
        <CS:getctag/>
    </D:prop>
</D:propfind>

更换$ XMLr-&gt; name!==&#39; product&#39;通过$ XMLr-&gt; name!==&#39; D:prop&#39;我得到一个白色的屏幕......

我做错了什么? 我怎样才能得到答案&#34; ressourcetype owner current-user-principal等...&#34; ?

2 个答案:

答案 0 :(得分:2)

我尝试使用XMLReadersimplexml_import_dom但没有成功,但相反,使用DomDocument可以做到:

// Just for display test results
$break_line = '<br>';
if (php_sapi_name() === 'cli') {
  $break_line = "\n";
}

$xml = '<?xml version="1.0" encoding="UTF-8"?>
<D:propfind xmlns:D="DAV:" xmlns:CS="http://calendarserver.org/ns/" xmlns:C="urn:ietf:params:xml:ns:caldav">
    <D:prop>
        <D:resourcetype/>
        <D:owner/>
        <D:current-user-principal/>
        <D:supported-report-set/>
        <C:supported-calendar-component-set/>
        <CS:getctag/>
    </D:prop>
</D:propfind>';

$xml_document = new DomDocument(); // http://fr2.php.net/manual/fr/class.domdocument.php
$xml_document->loadXML($xml); // Or load file with $xml_document->load('test.xml);
$elements = $xml_document->getElementsByTagName('prop'); 
// $elements is a DOMNodeList object: http://fr2.php.net/manual/fr/class.domnodelist.php
foreach($elements as $element) {
  // $element is a DOMElement object: http://fr2.php.net/manual/fr/class.domelement.php
  $childs = $element->childNodes;
  // $childs is DOMNodeList
  foreach ($childs as $child) {
    // $element is a DOMElement object
    if ($child instanceof DOMElement) {
      echo $child->nodeName . $break_line;
    }
  }

}

答案 1 :(得分:0)

白屏通常表示错误。

将error_reporting放在E_ALL

error_reporting('E_ALL');