Wednesday 1 January 2014

Create XML file and add/cascade css using php

The below example shows how to create a XML file using php and also shows how to add css on it.Here we are using "simplexml" php function. For more details, click here.

create a php file (index.php) and copy & past the below code

################### Start PHP Code #####################

<?php


class SimpleXMLElement_Plus extends SimpleXMLElement {

    public function addMyCss( $name, $value )
    {
        $dom_sxe = dom_import_simplexml($this);      
        $dom_parent = $dom_sxe->ownerDocument;      
        $xpath = new DOMXPath($dom_parent);
        $first_element = $xpath->evaluate('/*[1]')->item(0);
        $pi = $dom_parent->createProcessingInstruction($name, $value);
        $dom_parent->insertBefore($pi, $first_element);
    }
}


$xml = new SimpleXMLElement_Plus('<xml/>');
$xml->addMyCss('xml-stylesheet', 'type="text/css" href="cd_catalog.css"');
$track = $xml->addChild('markers');
for ($i = 1; $i <= 8; ++$i) {
    $marker = $xml->addChild('marker');
    $marker->addChild('name', "name$i");
    $marker->addChild('address', "address $i");
    $marker->addChild('lat', "lat $i");
    $marker->addChild('lng', "lng $i");
}

Header('Content-type: text/xml');
print($xml->asXML());

?>

################### End PHP Code #####################


Create a CSS file(cd_catalog.css) and copy and past the below code.


######################### Start CSS  ##################

markers
{
margin:10px;
background-color:#ccff00;
font-family:verdana,helvetica,sans-serif;
}

name
{
display:block;
font-weight:bold;
}

address, lat, lng
{
display:block;
color:#636363;
font-size:small;
font-style:italic;
}

########################## End CSS  ##################

If you have any questions, please post it as comments.

No comments:

Post a Comment