Sign up to create your own snipts, or login.

Public snipts » robertbanh's snipts » xml The latest xml snipts from robertbanh.

showing 1-5 of 5 snipts for xml
  • PHP XML Expat method
    <?php
    $current_tag = '';
    
    function startTag($parser, $name, $attr)
    {
        global $current_tag;
    	$current_tag = strtolower($name);
    }
    
    function endTag($parser, $name)
    {
        global $current_tag;
    	$current_tag = null;
    }
    
    //Function to use when finding character data
    function expatEngine($parser,$data)
    {
        global $current_tag;
        
        if ($current_tag == 'name')
        {
            echo "name = $data <br/>";
        }
        
    }
    
    //Specify data handler
    $xml_parser = xml_parser_create();
    xml_set_element_handler($xml_parser, "startTag", "endTag");
    xml_set_character_data_handler($xml_parser, "expatEngine");
    
    //Open XML file
    $fp=fopen("local-greatschools-feed-TX.xml","r");
    
    //Read data
    while ($data=fread($fp,8192))
    {
        xml_parse($xml_parser,$data,feof($fp)) or
        die (sprintf("XML Error: %s at line %d",
            xml_error_string(xml_get_error_code($xml_parser)),
            xml_get_current_line_number($xml_parser)));
    }
    
    //Free the XML parser
    xml_parser_free($xml_parser);
    fclose($fp);
    
    ?> 
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Apr 16, 2010 at 10:36 a.m. EDT
  • PHP Array to XML (with attributes)
    <?php
    //
    /*
        Example usage:
        ===============
        $xml = "
        <library id='123' test='456'>
            <book>
                <authorFirst>Mark</authorFirst>
                <authorLast>Twain</authorLast>
                <title>The Innocents Abroad</title>
            </book>
            <book>
                <authorFirst>Charles</authorFirst>
                <authorLast>Dickens</authorLast>
                <title>Oliver Twist</title>
            </book>
        </library>";
        
        echo "<pre>";
        var_export(ArrayToXML::xml2array($xml));
        ===============
        
        $library = array(
            'library' => array(
                '_a' => array( 'id'=>'1234', 'test'=>'456' ),
                '_c' => array( 'book' => array(
                    '_c' => array(
                        'authorFirst' => array( '_v' => 'Mark' ),
                        'authorLast'  => array( '_v' => 'Twain' ),
                        'title'       => array( '_v' => 'The Innocents Abroad' )
                        ),
                    '_c' => array(
                        'authorFirst' => array( '_v' => 'Charles' ),
                        'authorLast'  => array( '_v' => 'Dickens' ),
                        'title'       => array( '_v' => 'Oliver Twist' )
                        ),
                    )
                )
            )
        );
        header('Content-Type: application/xml');
        echo ArrayToXML::array2xml($library);
        
    */
    class ArrayToXML
    {
        // Array to XML
        public static function array2xml($cary, $d=0, $forcetag='') {
            $res=array();
            foreach ($cary as $tag=>$r) {
                if (isset($r[0])) {
                    $res[]=ArrayToXML::array2xml($r, $d, $tag);
                } else {
                    if ($forcetag) $tag=$forcetag;
                    $sp=str_repeat("\t", $d);
                    $res[]="$sp<$tag";
                    if (isset($r['_a'])) {foreach ($r['_a'] as $at=>$av) $res[]=" $at=\"$av\"";}
                    $res[]=">".((isset($r['_c'])) ? "\n" : '');
                    if (isset($r['_c'])) $res[]=ArrayToXML::array2xml($r['_c'], $d+1);
                    elseif (isset($r['_v'])) $res[]=$r['_v'];
                    $res[]=(isset($r['_c']) ? $sp : '')."</$tag>\n";
                }
                
            }
            return implode('', $res);
        }
        
        // XML to Array
        public static function xml2array(&$string) {
            $parser = xml_parser_create();
            xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
            xml_parse_into_struct($parser, $string, $vals, $index);
            xml_parser_free($parser);
    
            $mnary=array();
            $ary=&$mnary;
            foreach ($vals as $r) {
                $t=$r['tag'];
                if ($r['type']=='open') {
                    if (isset($ary[$t])) {
                        if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
                        $cv=&$ary[$t][count($ary[$t])-1];
                    } else $cv=&$ary[$t];
                    if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
                    $cv['_c']=array();
                    $cv['_c']['_p']=&$ary;
                    $ary=&$cv['_c'];
    
                } elseif ($r['type']=='complete') {
                    if (isset($ary[$t])) { // same as open
                        if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
                        $cv=&$ary[$t][count($ary[$t])-1];
                    } else $cv=&$ary[$t];
                    if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
                    $cv['_v']=(isset($r['value']) ? $r['value'] : '');
    
                } elseif ($r['type']=='close') {
                    $ary=&$ary['_p'];
                }
            }    
            
            ArrayToXML::_del_p($mnary);
            return $mnary;
        }
    
        // _Internal: Remove recursion in result array
        public static function _del_p(&$ary) {
            foreach ($ary as $k=>$v) {
                if ($k==='_p') unset($ary[$k]);
                elseif (is_array($ary[$k])) ArrayToXML::_del_p($ary[$k]);
            }
        }
        
        // Insert element into array
        public static function ins2ary(&$ary, $element, $pos) {
            $ar1=array_slice($ary, 0, $pos); $ar1[]=$element;
            $ary=array_merge($ar1, array_slice($ary, $pos));
        }
    }
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Feb 24, 2010 at 2:17 p.m. EST
  • PHP Array to XML
    <?php
    //
    // 
    /*
        Example usage:
        ===============
        <library>
            <book>
                <authorFirst>Mark</authorFirst>
                <authorLast>Twain</authorLast>
                <title>The Innocents Abroad</title>
            </book>
            <book>
                <authorFirst>Charles</authorFirst>
                <authorLast>Dickens</authorLast>
                <title>Oliver Twist</title>
            </book>
        </library>
        
        =================
        $library = array(
            'book' => array(
                array(
                    'authorFirst' => 'Mark',
                    'authorLast' => 'Twain',
                    'title' => 'The Innocents Abroad'
                ),
                array(
                    'authorFirst' => 'Charles',
                    'authorLast' => 'Dickens',
                    'title' => 'Oliver Twist'
                )
            )
        );
        header('Content-Type: application/xml');
        echo ArrayToXML::toXML($library, 'library');
    */
    
        
    class ArrayToXML
    {
        /**
         * The main function for converting to an XML document.
         * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
         *
         * @param array $data
         * @param string $rootNodeName - what you want the root node to be - defaultsto data.
         * @param SimpleXMLElement $xml - should only be used recursively
         * @return string XML
         */
        public static function toXML( $data, $rootNodeName = 'ResultSet', &$xml=null ) {
    
            // turn off compatibility mode as simple xml throws a wobbly if you don't.
            if ( ini_get('zend.ze1_compatibility_mode') == 1 ) ini_set ( 'zend.ze1_compatibility_mode', 0 );
            if ( is_null( $xml ) ) //$xml = simplexml_load_string( "" );
                $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
    
            // loop through the data passed in.
            foreach( $data as $key => $value ) {
    
                $numeric = false;
                
                // no numeric keys in our xml please!
                if ( is_numeric( $key ) ) {
                    $numeric = 1;
                    $key = $rootNodeName;
                }
    
                // delete any char not allowed in XML element names
                $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);
    
                // if there is another array found recrusively call this function
                if ( is_array( $value ) ) {
                    $node = ArrayToXML::isAssoc( $value ) || $numeric ? $xml->addChild( $key ) : $xml;
    
                    // recrusive call.
                    if ( $numeric ) $key = 'anon';
                    ArrayToXML::toXml( $value, $key, $node );
                } else {
    
                    // add single node.
                    $value = htmlentities( $value );
                    $xml->addChild( $key, $value );
                }
            }
    
            // pass back as XML
            return $xml->asXML();
    
        // if you want the XML to be formatted, use the below instead to return the XML
            //$doc = new DOMDocument('1.0');
            //$doc->preserveWhiteSpace = false;
            //$doc->loadXML( $xml->asXML() );
            //$doc->formatOutput = true;
            //return $doc->saveXML();
        }
    
    
        /**
         * Convert an XML document to a multi dimensional array
         * Pass in an XML document (or SimpleXMLElement object) and this recrusively loops through and builds a representative array
         *
         * @param string $xml - XML document - can optionally be a SimpleXMLElement object
         * @return array ARRAY
         */
        public static function toArray( $xml ) {
            if ( is_string( $xml ) ) $xml = new SimpleXMLElement( $xml );
            $children = $xml->children();
            if ( !$children ) return (string) $xml;
            $arr = array();
            foreach ( $children as $key => $node ) {
                $node = ArrayToXML::toArray( $node );
    
                // support for 'anon' non-associative arrays
                if ( $key == 'anon' ) $key = count( $arr );
    
                // if the node is already set, put it into an array
                if ( isset( $arr[$key] ) ) {
                    if ( !is_array( $arr[$key] ) || $arr[$key][0] == null ) $arr[$key] = array( $arr[$key] );
                    $arr[$key][] = $node;
                } else {
                    $arr[$key] = $node;
                }
            }
            return $arr;
        }
    
        // determine if a variable is an associative array
        public static function isAssoc( $array ) {
            return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
        }
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Feb 23, 2010 at 11:43 a.m. EST
  • XML (Simple XML) parse
    <?
    ==============================
    XML stuff (simple parse)
    
    // simple xml way
    
    // set the XML file name as a PHP string
    $myGroceryList = "output.xml" ; 
    // load the XML file 
    $xml = @simplexml_load_file($myGroceryList) or die ("no file loaded");
    // or load the string
    $xml = @simplexml_load_string($blah_string) or die ("error loading");
    
    echo var_export($xml);
    
    foreach ($xml->foodGroup as $foodGroup) {
      echo "<h2>Food group name is " . $foodGroup->groupName . "</h2>" ;
      foreach ($foodGroup->item as $foodItem) {
          echo "<br /> Item: " . $foodItem->name ;
          echo "<br /> Quantity: " . $foodItem->howMuch ;
          echo "<br />" ;
      }
      echo "<br />" ;
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 10, 2009 at 8:33 p.m. EDT
  • XML (SAX Parse) for PHP
    <?
    ==============================
    XML stuff (sax parse)
    
    // parse xml and store into array
    $xml_parser = xml_parser_create();
    xml_set_element_handler($xml_parser, "startTag", "endTag");
    xml_set_character_data_handler($xml_parser, "xmlEngine");
    $fp = fopen('xml/'.$xmlFile, "r") or die("Could not open file");
    
    // rbanh comment: apparently, for large sets of data the sax xml parser
    // tend to truncate data. So I'll have to create my own buffer to 
    // increase the size.
    $bufferCounter = 0;
    $bufferStorage = '';
    while( $data = fread( $fp, 8192 ) )
    {	
    	if ($bufferCounter % 2)
    	{
    		$bufferStorage .= $data;
    		xml_parse( $xml_parser, $bufferStorage );
    		$bufferStorage = '';
    	} else
    		$bufferStorage = $data;
    	
    	$bufferCounter++;
    }
    // make sure there isn't any more in the buffer
    if ($bufferStorage != '')
    	xml_parse( $xml_parser, $bufferStorage );
    xml_parser_free($xml_parser);
    fclose($fp); 
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 10, 2009 at 8:31 p.m. EDT
Sign up to create your own snipts, or login.