Tag Archive for xml

objects into array

function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
    $arrData = array();
   
    // if input is object, convert into array
    if (is_object($arrObjData)) {
        $arrObjData = get_object_vars($arrObjData);
    }
   
    if (is_array($arrObjData)) {
        foreach ($arrObjData as $index => $value) {
            if (is_object($value) || is_array($value)) {
                $value = objectsIntoArray($value, $arrSkipIndices); // recursive call
            }
            if (in_array($index, $arrSkipIndices)) {
                continue;
            }
            $arrData[$index] = $value;
        }
    }
    return $arrData;
}

source

DOM Parser demo using DocumentBuilder.

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class DocumentBuilderDemo {

	
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilder db = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		db = dbf.newDocumentBuilder();
		Document doc = db.parse(new File("c:simple.xml"));
		
		Element root = doc.getDocumentElement();
		System.out.println(root.getNodeName());
		
		System.out.println("========================================================================");
		
		NodeList nodeList = root.getElementsByTagName("to");
		
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i).getFirstChild();
			System.out.println(node.getNodeValue());
		}
		
		System.out.println("========================================================================");
		
		nodeList = root.getElementsByTagName("from");
		
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i).getFirstChild();
			System.out.println(node.getNodeValue());
		}
		
		System.out.println("========================================================================");
		
		nodeList = root.getElementsByTagName("body");
		
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i).getFirstChild();
			System.out.println(node.getNodeValue());
		}
	
		System.out.println("========================================================================");
	
		
	}

}


/*
The simple.xml file that we used for parsing in above example.


<?xml version="1.0"?>
<msg>
	<note>
		<to>Tom</to>
		<from>Prince</from>
		<heading>Reminder</heading>
		<body>Hello how are u?</body>
	</note>
	<note>
		<to>Sania</to>
		<from>Prince</from>
		<heading>Joking</heading>
		<body>Welcome!!!</body>
	</note>
</msg>

*/

source

Reading XML String As Table

/* Reading XML String As Table

Sample XML String
<employees>
    <employee><name>Hubert</name><age>19</age></employee>
    <employee><name>Gaye</name><age>12</age></employee>
</employees>

<employees>
    <employee name="Hubert" age="19" />
    <employee name="Gaye" age="12" />
</employees>

*/

ALTER PROCEDURE [dbo].[spInsertToTest]
    @xml text
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @hdoc int

    EXEC sp_xml_preparedocument @hdoc OUTPUT, @xml
    
    INSERT test
    SELECT *
    FROM OPENXML(@hdoc, '/employees/employee', 3)
        WITH ([name] varchar(50), age int)

    EXEC sp_xml_removedocument @hdoc    

END

source

Cleaning up NameSpaces

str = str.replace(/s+xmlns(:[^=]+)?="[^"]*"/g, "");

source

csv2xml perl version

#! /usr/bin/perl
use warnings;
use strict;
use Text::CSV;

# generate XML from CSV files
#


my $csv = Text::CSV->new(
    {
        binary => 1, # binary for utf8, latin1 etc
        sep_char => "	"
    }
) or die "Cannot use CSV: ".Text::CSV->error_diag ();

$csv->eol("
");

binmode(STDIN, ":utf8");
binmode(STDOUT, ":utf8");

foreach (@ARGV) {
    open my $input, "<:encoding(utf8)", $_ or die "test.csv: $!";

    print "<csv filename="$_">";
    while (my $colref = $csv->getline($input)) {
        print "<row>" .
        join("", map { "<cell>$_</cell>" } @$colref ) .
              "</row>
";
    }
    print "</csv>
";
}

source

Skip empty XML nodes

<xsl:template name="getValue">
    <xsl:param name="tagId"></xsl:param>
    <xsl:choose>
      <xsl:when test="normalize-space(//item[@id=$tagId]) != ''">
        not empty
      </xsl:when>
      <xsl:otherwise>
        EMPTY
      </xsl:otherwise>
    </xsl:choose>
    Value:<xsl:value-of select="string(//item[@id=$tagId])"/>:
  </xsl:template>

source

Retrieve Twitter Status using PHP and XML

<?php

class xmlmanager{
	
	private $twitterXML;
	private $twitterURL = ""; //insert xml url here
	private $dom;
	
	function __construct(){
	
	}
	
	function GetTwitterXML(){
		
		$this->twitterXML = simplexml_load_file($this->twitterURL);
		
		return ;
		
	}
	
	function save_twitter_xml_as_file(){
		$this->dom = new DOMDocument();
		$this->dom->loadXML($this->twitterXML->asXML());
		$this->dom->saveXML();
		$this->dom->save('mytwitter.xml');
		return ;
	}
	
	function __destruct(){
	
	}
}

?>

source

Creating an array of objects to store atom rss data

<?php
error_reporting(E_ALL); // shows all errors, remove this on live sites

$feedURL = '<a href="http://mydomain.com/rss/example.xml';" >http://mydomain.com/rss/example.xml';</a>
$getFILE = get_content($feedURL) or die("feed not loading");
$xml = simplexml_load_string($getFILE, NULL, LIBXML_NOCDATA); // Set CDATA as text nodes
$xml->registerXPathNamespace('atom', '<a href="http://www.w3.org/2005/Atom');" >http://www.w3.org/2005/Atom');</a> // define namespace atom

    class oEntry
    {
        public $url;
        public $author;
        public $date;
        public $text;
        
        function oEntry($url, $author, $date, $text) {
        	$this->url = $url;
        	$this->author = $author;
        	$this->date = $date;
        	$this->text = $text;
        }
    } 

	foreach($xml->xpath('atom:entry') as $entry) {
		// array of objects
		$e[] = new oEntry($xml->link['href'], $entry->author->name, $entry->published, $entry->content); 	
	} // end foreach

?>

SAMPLE XML INPUT (you need to fill out the tags):
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="<a href="http://www.w3.org/2005/Atom"" >http://www.w3.org/2005/Atom"</a> xmlns:thr="<a href="http://purl.org/syndication/thread/1.0">" >http://purl.org/syndication/thread/1.0"></a>
  <link rel="alternate" type="text/html" href="" />
  <id></id>
  <updated></updated>
  <title></title>
  
  <entry>
    <id></id>
    <thr:in-reply-to ref="" type="text/html" href=""/>
    <link rel="alternate" type="text/html" href="" />
    <title></title>
    <author>
        <name></name>
        <uri></uri>
    </author>
    <content type="html" xml:lang="en-us" xml:base="">
        <![CDATA[<p>html text goes here</p>]]>
    </content>
    <published>February 20, 2010  2:23 AM</published>
  </entry>

</feed>

source

Parse an xml file using jQuery

function parseXml(xml) {
  //find every Tutorial and print the author
  $(xml).find("Tutorial").each(function()
  {
    $("#output").append($(this).attr("author") + "");
  });
}

source

Kohana Feed With Attributes & Namespace Support

<?
class Feed2 extends feed {
	/**
	 * Creates a feed from the given parameters.
	 *
	 * @param   array   feed information
	 * @param   array   items to add to the feed
	 * @param   string  define which format to use
	 * @param   string  define which encoding to use
	 * @return  string
	 */
	public static function create($info, $items, $format = 'rss2', $encoding = 'UTF-8')
	{
		$info += array('title' => 'Generated Feed', 'link' => '', 'generator' => 'KohanaPHP');

		// handle namespaces
		$namespaceString = '';
		
		if(isset($info['namespaces'])) {
			foreach($info['namespaces'] as $prefix => $ns) {
				// can't add namespaces using the api bc it adds in xmlns:xmlns="..." which is explicitly declared as invalid xml: <a href="http://www.w3.org/TR/REC-xml-names/#xmlReserved" >http://www.w3.org/TR/REC-xml-names/#xmlReserved</a>
				// $feed->addAttribute('xmlns:'.$prefix, $ns, '<a href="http://www.w3.org/2000/xmlns/');" >http://www.w3.org/2000/xmlns/');</a>
				
				$namespaceString .= " xmlns:".$prefix.'="'.$ns.'"';
			}
			
			$namespaces = $info['namespaces'];
			
			// this is so it is not included in the rest of the $info generation
			unset($info['namespaces']);
		}
		
		$feed = '<?xml version="1.0" encoding="'.$encoding.'"?><rss version="2.0"'.$namespaceString.'><channel></channel></rss>';
		$feed = simplexml_load_string($feed);
		
		foreach ($info as $name => $value)
		{
			if (($name === 'pubDate' OR $name === 'lastBuildDate') AND (is_int($value) OR ctype_digit($value)))
			{
				// Convert timestamps to RFC 822 formatted dates
				$value = date(DATE_RFC822, $value);
			}
			elseif (($name === 'link' OR $name === 'docs') AND strpos($value, '<a href="://')" >://')</a> === FALSE)
			{
				// Convert URIs to URLs
				$value = url::site($value, 'http');
			}

			// Add the info to the channel
			$feed->channel->addChild($name, $value);
		}

		foreach ($items as $item)
		{
			// Add the item to the channel
			$row = $feed->channel->addChild('item');

			foreach ($item as $name => $value)
			{
				if(!is_array($value)) {
					if ($name === 'pubDate' AND (is_int($value) OR ctype_digit($value)))
					{
						// Convert timestamps to RFC 822 formatted dates
						$value = date(DATE_RFC822, $value);
					}
					elseif (($name === 'link' OR $name === 'guid') AND strpos($value, '<a href="://')" >://')</a> === FALSE)
					{
						// Convert URIs to URLs
						$value = url::site($value, 'http');
					}
					
					// Add the info to the row
					$row->addChild($name, $value);
				} else {
					$child = $row->addChild($name);
					
					// If the value is an array we are specifying attributes
					foreach($value as $attribute => $attributeValue) {
						if(strchr($attribute, ':') !== FALSE) {
							list($ns, $attribute2) = explode(':', $attribute);
						} else {
							$ns = "";
						}
						
						//!empty($ns) ? $namespaces[$ns] : NULL
						$child->addAttribute($attribute, $attributeValue, !empty($ns) ? $namespaces[$ns] : NULL);
					}
				}
			}
		}

		return $feed->asXML();
	}
}

// Example Feed Generation (For Sparkle Update System):

$feedItems = array();

foreach(ORM::factory('updates')->find_all() as $clientUpdate) {
	$feedItems[] = array(
		'title' => 'v'.$clientUpdate->version,
		'pubDate' => $clientUpdate->date,
		'enclosure' => array(
			'url' => '<a href="http://domain.com/'," >http://domain.com/',</a>
			'type' => 'application/octet-stream',
			'length' => filesize('/path/to/file.zip'),
			'sparkle:dsaSignature' => 'dsasig',
			'sparkle:version' => '200',
			'sparkle:shortVersionString' => '1.0',
			'sparkle:minimumSystemVersion' => '10.6'
		)
	);
}

$feedData = feed2::create(
	array(
		'title' => 'Update Feed',
		'author' => 'Michael Bianco',
		'pubDate' => date('r'),
		'link' => '<a href="http://domain.com/'," >http://domain.com/',</a>
		'language' => 'en',
		'namespaces' => array(
			'sparkle' => '<a href="http://www.andymatuschak.org/xml-namespaces/sparkle'," >http://www.andymatuschak.org/xml-namespaces/sparkle',</a>
			'dc' => '<a href="http://purl.org/dc/elements/1.1/'" >http://purl.org/dc/elements/1.1/'</a>
		)
	),
	$feedItems
);

?>

source