2011-09-28 33 views
-1

評價請原諒我缺乏的是如何工作的理解!如果你不準備幫忙,請不要打擾張貼。謝謝!XSL tansform結果在PHP

我:

$XML = new DOMDocument(); 
$XML->load('demo.xml'); 

$xpath = new DOMXpath($XML); 
$elements = $xpath->evaluate($_GET["xpath"]); 

$XSL = new DOMDocument(); 
$XSL->load('xml2json.xsl', LIBXML_NOCDATA); 

$xslt = new XSLTProcessor(); 
$xslt->importStylesheet($XSL); 

echo $xslt->transformToXML($elements); 

我得到以下錯誤:

(!) Warning: XSLTProcessor::transformToXml() [xsltprocessor.transformtoxml]: Invalid Document in C:\wamp\www\content.php on line 18 

如何轉換的DOMNodeList到一個DOMDocument,使這項工作?

這是我如何得到它的工作!

function getContent(&$NodeContent="",$nod) 
{ $NodList=$nod->childNodes; 
    for($j=0 ; $j < $NodList->length; $j++) 
    {  $nod2=$NodList->item($j);//Node j 
     $nodemane=$nod2->nodeName; 
     $nodevalue=$nod2->nodeValue; 
     if($nod2->nodeType == XML_TEXT_NODE) 
      $NodeContent .= $nodevalue; 
     else 
     {  $NodeContent .= "<$nodemane"; 
      $attAre=$nod2->attributes; 
      foreach ($attAre as $value) 
       $NodeContent .=" {$value->nodeName}='{$value->nodeValue}'" ; 
      $NodeContent .=">";      
      getContent($NodeContent,$nod2);      
      $NodeContent .= "</$nodemane>"; 
     } 
    } 

} 


$XML = new DOMDocument(); 
$XML->load('demo.xml'); 

$xpath = new DOMXpath($XML); 
$elements = $xpath->query($_GET["xpath"]); 

$XSL = new DOMDocument(); 
$XSL->load('xml2json.xsl', LIBXML_NOCDATA); 

$xslt = new XSLTProcessor(); 
$xslt->importStylesheet($XSL); 

$newdoc = new DOMDocument; 
$newdoc -> preserveWhiteSpace = false; 
$newdoc -> formatOutput = true; 

$elm = $elements->item(0); 
getContent($docstring,$elm); 
$docstring = '<root>'.$docstring.'</root>'; 
$docstring = str_replace(array("\r\n", "\r", "\n", "\t"), '', $docstring); 
$newdoc -> LoadXML($docstring); 
echo $xslt->transformToXML($newdoc); 
+1

應該有一個結束標誌爲「RTFE」。 – salathe

回答

1

你正在做

$elements = $xpath->evaluate($_GET["xpath"]); 
… 
echo $xslt->transformToXML($elements); 

return values for DOMXPath::evaluate()

Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression. If the expression is malformed or the contextnode is invalid, DOMXPath::evaluate() returns FALSE .

method signature for transformToXML()狀態

string XSLTProcessor::transformToXML (DOMDocument $doc) 

換句話說,你是不是傳遞一個DOMDocument,並獲得「無效文檔」錯誤。

+1

嗨,是的,但是如何在本例中將其轉換爲文檔? –

+0

創建一個新的DOMDocument。導入並追加結果節點。 – Gordon

+0

謝謝我確實遇到了問題,我只是沒有解決方案。我有搜索從DOMNodeList創建一個DOMDocument沒有運氣。你能提供一個代碼示例嗎? –