Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Friday, March 2, 2012

Create Dynamic Links With XSL

This would go inside a process loop such as:

where param1 and param2 are children inside your XML document.


http://example.com/?param1=
&param2=


Link Text

How To Add An XSL Stylesheet To PHP DOMDocument

<?php
$xslAttributes = 'href="sample.xsl" type="text/xsl"';
$xmlStylesheet = new DOMProcessingInstruction('xml-stylesheet',$xslAttributes);

$doc = new DOMDocument('1.0','UTF-8');
$doc->appendChild($xmlStylesheet);
?>

Friday, September 16, 2011

Iterate Over Nested / Multi-Level DOM NodeList

<?php
function processNodeList($nodeList)
{
    # text nodes don't have child nodes
    if ($root->nodeName == '#text')
    {
        $xml = $root->nodeValue;
    }
    else
    {
        # start tag
        $xml = sprintf('<%s>', $root->nodeName);
        # contents
        foreach ($root->childNodes as $node)
        {
            $xml .= processNodeList($node);
        }
        #end tag
        $xml .= sprintf('', $root->nodeName);
        # for some reason the blog puts html comment tags around the closing sprintf, just FYI to remove those as they are not intended
    }
    return $xml;
}

$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);

$nodeList = $xpath->query('/');
$xml = processNodeList($nodeList);

echo $xml; 
?>

Thursday, September 1, 2011

Import Xpath Query NodeList To A New XML Document

<?php

$doc = new DOMDocument();
$doc->loadxml($xml); //XML STRING
$xpath = new DOMXpath($doc);
$xpathResults = $xpath->query(""); //YOUR QUERY
$nodes = $xpathResults->length;

if($nodes > 0)
{
 $newDom = new DOMDocument('1.0','UTF-8');
 $root = $newDom->createElement('root');
 $root = $newDom->appendChild($root);
 
 foreach ($xpathResults as $domElement)
 {
  $domNode = $newDom->importNode($domElement, true);
  $root->appendChild($domNode);
  $newXML = $newDom->saveXML();     
 }   
 header("Content-type: application/xml");
 echo $newXML;
} 

?>

Friday, January 22, 2010

Conditionally query specific elements within an XML document

Given:

     the name
     the desc
     misc garbage
     1


Suppose you had 100 of these and wanted to obtain just the name and description for a specific id

<?php
$doc = simplexml_load_string();

$results = $doc->xpath("//tree[contains(id,'1')]/child::*[self::name or self::desc]"); 

?>

That will get the job done