Output Raw Xml Using PHP

Output raw XML using php

By default PHP sets the Content-Type to text/html, so the browsers are displaying your XML document as an HTML page.

For the browser to treat the document as XML you have to set the content-type:

header('Content-Type: text/xml');

Do this before printing anything in your script.

How to display raw xml file in php to web browser

You do not have to use the simplexml_load_file: there is another function to read a file, this function is file_get_contents($filename).

Here is a simple code to use:

<?php
// Set the encoding to XML
header('Content-type: text/xml');

// Get contents of the file
$xml = file_get_contents("xmlfile.xml") ;

// Print contents
echo $xml;

?>

I hope it helped you! And sorry for the language mistakes ;)

Write raw xml in a SimpleXMLElement

SimpleXML doesn't have this ability directly, but it is available in the DOM family of functions. Thankfully, it is easy to work with SimpleXML and DOM at the same time on the same XML document.

The example below uses a document fragment to add a couple of elements to a document.

<?php

$example = new SimpleXMLElement('<example/>');

// <example/> as a DOMElement
$dom = dom_import_simplexml($example);

// Create a new DOM document fragment and put it inside <example/>
$fragment = $dom->ownerDocument->createDocumentFragment();
$fragment->appendXML('<a>a</a><b>b</b>');
$dom->appendChild($fragment);

// Back to SimpleXML, it can see our document changes
echo $example->asXML();

?>

The above example outputs:

<?xml version="1.0"?>
<example><a>a</a><b>b</b></example>

how to display xml content with php

You can redirect to this file:

<?php header('Location: '.$xmlFile); ?>

Your browser will dispay the content of the file

How to output XML string from PHP

Before you print, add content type header.

Either

header('Content-type: text/xml');

or more proper for KML

header('Content-type: application/vnd.google-earth.kml+xml');

If you want to view it in the browser as source, read this: http://www.w3schools.com/xml/xml_view.asp

You can also force it to be displayed as text, by adding

 header('Content-type: text/plain');

return raw XML from xpath query in PHP?

$doc = new DOMDocument();
$doc->loadXML('<root>...</root>'); // or $doc->load($file) if loading from file
$xpath = new DOMXpath($doc);
$elements = $xpath->query("/root/row[@id='1']");
if ($elements) {
foreach ($elements as $item) {
echo $doc->saveXML($item), "\n";
}
}

thanks to @fab's comment. I forgot that.

echo -ing xml data from sql database via php script

Any text that starts with < followed by letter. Use htmlentities() function to output any HTML code as plain text.

To output HTML data with < encoded to <



Related Topics



Leave a reply



Submit