2012-07-08 2 views
0

변환 한 XML 문서가 있으며 브라우저에서보고 디렉토리에 저장합니다.변환 후 XML 헤더 정보 추가

저장된 버전의 파일에 연결된 스타일 시트를 추가하고 싶습니다. 나는 아래의 str_replace (잘못된 사용법 일 수 있음) 및 xsl 처리 명령어를 사용하여 시도했다.

xsl 처리 명령어가 어느 정도 작동했습니다. 브라우저에서 소스를 보면 스타일 시트 링크가 표시되지만이 정보는 저장된 파일에 저장되지 않습니다 !!

원시 XML 파일을 스타일 시트로 변환하고 디렉토리에 저장 한 다음 xsl 스타일 시트를 새 파일의 헤더에 추가하면 새로 저장된 xml 파일이 열릴 때 유용합니다. 브라우저에서 스타일 시트가 자동으로 적용됩니다. 희망이 이해가!

내 코드는 다음과 같습니다.

//write to the file 
$id = $_POST['id'];//xml id 
$path = 'xml/';//send to xml directory 
$filename = $path. $id . ".xml"; 
$header = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '<?xml version="1.0"  encoding="UTF-8" ?><?xml-stylesheet type="text/xsl" href="../foo.xsl"?>'); 
$article->asXML($filename);//saving the original xml as new file with posted id 

$xml = new DOMDocument; 
$xml->load($filename); 

$xsl = new DOMDocument; 
$xsl->load('insert.xsl'); 

$proc = new XSLTProcessor; 
$proc->importStyleSheet($xsl); 

echo $proc->transformToXML($xml); 

미리 감사드립니다.

+0

저는 포함 된 XSLT 스타일 시트를 지원하는 브라우저를 알지 못합니다. 이것을 성공적으로 시도 했습니까? –

답변

1

XSLT 파일에 <xsl:processing-instruction/> 태그를 사용하여 스타일 시트 링크를 추가 할 수 있습니다.

<xsl:processing-instruction name="xml-stylesheet"> 
    type="text/xsl" href="../foo.xsl" 
</xsl:processing-instruction> 

이 생산하는 것 :

<?xml-stylesheet type="text/xsl" href="../foo.xsl"?> 

Alternativly, 당신은 DOMDocument 함께 할 수 있습니다.

$newXml = $proc->transformToXML($xml); 

// Re-create the DOMDocument with the new XML 
$xml = new DOMDocument; 
$xml->loadXML($newXml); 

// Find insertion-point 
$insertBefore = $xml->firstChild; 
foreach($xml->childNodes as $node) 
{ 
    if ($node->nodeType == XML_ELEMENT_NODE) 
    { 
    $inertBefore = $node; 
    break; 
    } 
} 

// Create and insert the processing instruction 
$pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="../foo.xsl"'); 
$xml->insertBefore($pi, $insertBefore); 

echo $xml->saveXML(); 
+0

고마워, 이건 나를 위해 작동하지 않습니다. PHP와 함께 할 수있는 방법이 있습니까? – wec

+0

@wec 여기 있습니다. –

+0

우수 감사합니다! – wec