Fetching a remote XML document in PHP
<?php $url = 'http://rss.news.yahoo.com/rss/omg'; $rss = simplexml_load_file($url); print '<ul>'; foreach ($rss->channel->item as $item) { print '<li><a href="' . htmlentities($item->link) . '">' . htmlentities($item->title) . '</a></li>'; } print '</ul>'; ?>
Generate Atom feeds from your data
class atom1 extends DOMDocument { private $ns; public function __construct($title, $href, $name, $id) { parent::__construct(); $this->formatOutput = true; $this->ns = 'http://www.w3.org/2005/Atom'; $root = $this->appendChild($this->createElementNS($this->ns, 'feed')); $root->appendChild($this->createElementNS($this->ns, 'title', $title)); $link = $root->appendChild($this->createElementNS($this->ns, 'link')); $link->setAttribute('href', $href); $root->appendChild($this->createElementNS($this->ns, 'updated', date('Y-m-d\\TH:i:sP'))); $author = $root->appendChild($this->createElementNS($this->ns, 'author')); $author->appendChild($this->createElementNS($this->ns, 'name', $name)); $root->appendChild($this->createElementNS($this->ns, 'id', $id)); } public function addEntry($title, $link, $summary) { $entry = $this->createElementNS($this->ns, 'entry'); $entry->appendChild($this->createElementNS($this->ns, 'title', $title)); $entry->appendChild($this->createElementNS($this->ns, 'link', $link)); $id = uniqid('http://example.org/atom/entry/ids/'); $entry->appendChild($this->createElementNS($this->ns, 'id', $id)); $entry->appendChild($this->createElementNS($this->ns, 'updated', date(DATE_ATOM))); $entry->appendChild($this->createElementNS($this->ns, 'summary', $summary)); $this->documentElement->appendChild($entry); } } $atom = new atom1('Channel Title', 'http://www.example.org', 'Atom', 'http://example.org/atom/feed/ids/1'); $atom->addEntry('Item 1', 'http://www.example.org/item1', 'Item 1 Description', 'http://example.org/atom/entry/ids/1'); $atom->addEntry('Item 2', 'http://www.example.org/item2', 'Item 2 Description', 'http://example.org/atom/entry/ids/2'); print $atom->saveXML();
Output:
Generate RSS feeds from your data
<?php class rss2 extends DOMDocument { private $channel; public function __construct($title, $link, $description) { parent::__construct(); $this->formatOutput = true; $root = $this->appendChild($this->createElement('rss')); $root->setAttribute('version', '2.0'); $channel= $root->appendChild($this->createElement('channel')); $channel->appendChild($this->createElement('title', $title)); $channel->appendChild($this->createElement('link', $link)); $channel->appendChild($this->createElement('description', $description)); $this->channel = $channel; } public function addItem($title, $link, $description) { $item = $this->createElement('item'); $item->appendChild($this->createElement('title', $title)); $item->appendChild($this->createElement('link', $link)); $item->appendChild($this->createElement('description', $description)); $this->channel->appendChild($item); } } $rss = new rss2('Channel Title', 'http://www.example.org', 'Channel Description'); $rss->addItem('Item 1', 'http://www.example.org/item1', 'Item 1 Description'); $rss->addItem('Item 2', 'http://www.example.org/item2', 'Item 2 Description'); print $rss->saveXML(); ?>
<?xml version="1.0"?> <rss version="2.0"> <channel> <title>Channel Title</title> <link>http://www.example.org</link> <description>Channel Description</description> <item> <title>Item 1</title> <link>http://www.example.org/item1</link> <description>Item 1 Description</description> </item> <item> <title>Item 2</title> <link>http://www.example.org/item2</link> <description>Item 2 Description</description> </item> </channel> </rss>
Access channel attribute using MagpieRSS
<?php $feed = 'http://feeds.feedburner.com/w3mentor?format=rss'; $rss = fetch_rss($feed); print "<ul>\n"; foreach ($rss->channel as $key => $value) { print "<li>$key: $value</li>\n"; } print "</ul>\n"; ?>
Reading RSS and Atom Feeds using MagpieRSS parser
Using the MagpieRSS parser here’s an example that reads the RSS feed.
<?php require 'rss_fetch.inc'; $feed = 'http://feeds.feedburner.com/w3mentor?format=rss'; $rss = fetch_rss( $feed ); print "<ul>\n"; foreach ($rss->items as $item) { print '<li><a href="' . $item['link'] . '">' . $item['title'] . "</a></li>\n"; } print "</ul>\n"; ?>
Handling Content Encoding in PHP XML
Use the iconv library to convert it before passing it into an XML extension:
$utf_8 = iconv('ISO-8859-1', 'UTF-8', $iso_8859_1);
Then convert it back when you are finished:
$iso_8859_1 = iconv('UTF-8', 'ISO-8859-1', $utf_8);
Validating XML String using PHP
With XML in a string, call DOMDocument::schemaValidateSource() or DOMDocument::relaxNGValidateSource():
$xml = '<person><firstname>Raja</firstname></person>'; $schema = 'address.xsd'; $ab = new DOMDocument $ab->load($file); if ($ab->>schemaValidateSource($schema)) { print "XML is valid.\n"; } else { print "XML is invalid.\n"; }
Validating XML Documents using PHP
With existing DOM objects, call DOMDocument::schemaValidate( ) or DOMDocument::relaxNGValidate( ):
$file = 'addresses.xml'; $schema = 'addresses.xsd'; $ab = new DOMDocument $ab->load($file); if ($ab->schemaValidate($schema)) { print "$file is valid.\n"; } else { print "$file is invalid.\n"; }
Call user defined functions from XSL
function replace_email($nodes) { return preg_replace('/([^@\s]+)@([-a-z0-9]+\.)+[a-z]{2,}/is', '$1@...', $nodes[0]->nodeValue); } $dom = new DOMDocument; $dom->load('addresses.xml'); $xsl = new DOMDocument $xsl->load('stylesheet.xsl'); $xslt = new XSLTProcessor(); $xslt->importStylesheet($xsl); $xslt->registerPhpFunctions(); print $xslt->transformToXML($dom);
Stylesheet.xsl
<?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" xsl:extension-element-prefixes="php"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="/addresses/person/email"> <xsl:copy> <xsl:value-of select="php:function('replace_email', node())" /> </xsl:copy> </xsl:template> </xsl:stylesheet>
Input XML:
<?xml version="1.0"?> <addresses> <person> <name>Ramesh babu</name> <firstname>Ramesh</firstname> <lastname>babu</lastname> <email>Ram@w3mauthor.com</email> </person> <person> <name>Jolld babu</name> <firstname>jolld</firstname> <lastname>babu</lastname> <email>Jolld@w3mauthor</email> </person> </addresses>
Calling PHP Functions from XSLT Stylesheets
Invoke the XSLTProcessor::registerPHPFunctions( ) method to enable this functionality:
$xslt = new XSLTProcessor(); $xslt->registerPHPFunctions();
And use the function( ) or functionString( ) function within your stylesheet:
<?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" xsl:extension-element-prefixes="php"> <xsl:template match="/"> <xsl:value-of select="php:function('strftime', '%c')" /> </xsl:template> </xsl:stylesheet>
Set XSLT Parameters from PHP
Use the XSLTProcessor::setParameter( ) method: The first argument is the namespace and can be null
$uid = '123'; $dom = new DOMDocument $dom->load('addresses.xml'); $xsl = new DOMDocument $xsl->load('stylesheet.xsl'); $xslt = new XSLTProcessor(); $xslt->importStylesheet($xsl); $xslt->setParameter(NULL, 'user_id', $uid); print $xslt->transformToXML($dom);
stylesheet.xsl:
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/addresses/person">
<xsl:if test="userid=$user_id">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:if>
</xsl:template>
</xsl:stylesheet>Check if XSLT Transformation failed
// Load XSL template $xsl = newDOMDocument; $xsl->load('stylesheet.xsl'); // Create new XSLTProcessor $xslt = new XSLTProcessor(); // Load stylesheet $xslt->importStylesheet($xsl); // Load XML input file $xml = new DOMDocument; $xml->load('data.xml'); // Transform to string $results = $xslt->transformToXML($xml); // Transform to a file $results = $xslt->transformToURI($xml, 'results.txt'); // Transform to DOM object $results = $xslt->transformToDoc($xml); if (false === ($results = $xslt->transformToXML($xml))) { // an error occurred }
Transforming XML with XSLT
Use PHP’s XSLT extension:
// Load XSL template $xsl = newDOMDocument; $xsl->load('stylesheet.xsl'); // Create new XSLTProcessor $xslt = new XSLTProcessor(); // Load stylesheet $xslt->importStylesheet($xsl); // Load XML input file $xml = new DOMDocument; $xml->load('data.xml'); // Transform to string $results = $xslt->transformToXML($xml); // Transform to a file $results = $xslt->transformToURI($xml, 'results.txt'); // Transform to DOM object $results = $xslt->transformToDoc($xml);
The transformed text is stored in $results.
Using XPath with SimpleXML
$s = simplexml_load_file('addresses.xml'); $people = $s->xpath('/addresses/person'); foreach($people as $p) { list($firstname) = $p->xpath('firstname'); list($lastname) = $p->xpath('lastname'); print "$firstname $lastname\n"; }
Input XML:
<?xml version="1.0"?> <addresses> <person> <name>Ramesh babu</name> <firstname>Ramesh</firstname> <lastname>babu</lastname> <email>Ram@w3mauthor.com</email> </person> <person> <name>Jolld babu</name> <firstname>jolld</firstname> <lastname>babu</lastname> <email>Jolld@w3mauthor</email> </person> </addresses>
Using XPath with DOM
$dom = new DOMDocument; $dom->load('addresses.xml'); $xpath = new DOMXPath($dom); $person = $xpath->query('/addresses/person'); foreach ($person as $p) { $fn = $xpath->query('firstname', $p); $firstname = $fn->item(0)->firstChild->nodeValue; $ln = $xpath->query('lastname', $p); $lastname = $ln->item(0)->firstChild->nodeValue; print "$firstname $lastname\n"; }
Input XML:
<?xml version="1.0"?> <addresses> <person> <name>Ramesh babu</name> <firstname>Ramesh</firstname> <lastname>babu</lastname> <email>Ram@w3mauthor.com</email> </person> <person> <name>Jolld babu</name> <firstname>jolld</firstname> <lastname>babu</lastname> <email>Jolld@w3mauthor</email> </person> </addresses>
Get Information Using XPath in DOM
<?php $dom = new DOMDocument; $dom->load('addresses.xml'); $xpath = new DOMXPath($dom); $email = $xpath->query('/addresses/person/email'); foreach ($emails as $email) { // do something with $email } ?>
Input XML:
<?xml version="1.0"?> <addresses> <person> <name>Ramesh babu</name> <email>Ram@w3mauthor.com</email> </person> <person> <name>Jolld</name> <email>Jolld@w3mauthor</email> </person> </addresses>
Get Information Using XPath in simpleXML
XPath is available in SimpleXML:
<?php $s = simplexml_load_file('addresses.xml'); $emails = $s->xpath('/addresses/person/email'); foreach ($emails as $email) { // do something with $email } ?>
Input XML:
<?xml version="1.0"?> <addresses> <person> <name>Ramesh babu</name> <email>Ram@w3mauthor.com</email> </person> <person> <name>Jolld</name> <email>Jolld@w3mauthor</email> </person> </addresses>
XMLReader node type values
| Node type | Description |
|---|---|
| XMLReader::NONE | No node type |
| XMLReader::ELEMENT | Start element |
| XMLReader::ATTRIBUTE | Attribute node |
| XMLReader::TEXT | Text node |
| XMLReader::CDATA | CDATA node |
| XMLReader::ENTITY_REF | Entity Reference node |
| XMLReader::ENTITY | Entity Declaration node |
| XMLReader::PI | Processing Instruction node |
| XMLReader::COMMENT | Comment node |
| XMLReader::DOC | Document node |
| XMLReader::DOC_TYPE | Document Type node |
| XMLReader::DOC_FRAGMENT | Document Fragment node |
| XMLReader::NOTATION | Notation node |
| XMLReader::WHITESPACE | Whitespace node |
| XMLReader::SIGNIFICANT_WHITESPACE | Significant Whitespace node |
| XMLReader::END_ELEMENT | End Element |
| XMLReader::END_ENTITY | End Entity |
| XMLReader::XML_DECLARATION | XML Declaration node |
Parsing Large XML Documents using XMLReader
Use the XMLReader extension:
$reader = new XMLReader();
$reader->open(‘input.xml’);
/* Loop through document */
while ($reader->read()) {
if ($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == ‘author’) {
$reader->read();
print $reader->value . “\n”;
}
}
?>
Input XML:
<?xml version="1.0"?> <books> <book> <title>Learn PHP XML</title> <author>w3mauthor</author> <author>w3mauthor1</author> <subject>PHP</subject> </book> <book> <title>Learn Perl</title> <author>w3mauthor</author> <author>w3mauthor1</author> <subject>Perl</subject> </book> </books>
Printing all nodes using getElementsByTagname in DOM
// find and print all authors $authors = $dom->getElementsByTagname('author'); // loop through author elements foreach ($authors as $author) { // childNodes holds the author values $text_nodes = $author->childNodes; foreach ($text_nodes as $text) { print $text->nodeValue . "\n"; } }
Input XML:
<?xml version="1.0"?> <books> <book> <title>Learn PHP XML</title> <author>w3mauthor</author> <author>w3mauthor1</author> <subject>PHP</subject> </book> <book> <title>Learn Perl</title> <author>w3mauthor</author> <author>w3mauthor1</author> <subject>Perl</subject> </book> </books>
