Hey there i'm trying to generate an XML file with php variables.
but echo or print don't seem to work watch my snippet below.
How could i achieve what i'm trying todo?
$xml = new DOMDocument();
$root = $xml->createElement('package');
$root = $xml->appendChild($root);
$title = $xml->createElement('id' , echo $_GET['bundleid']);
$title = $root->appendChild($title);
As luenib pointed out, you generally don't put "echo" before variables that you pass to functions as arguments. Below is a simple example of outputting XML to browser or writing to file.
$xml = new DOMDocument();
$root = $xml->createElement('package');
$root = $xml->appendChild($root);
$title = $xml->createElement('id' , $_GET['bundleid']); // no "echo" before variable
//$title = $xml->createElement('id' , $_POST['bundleid']);
//$title = $xml->createElement('id' , $bundleid);
//$title = $xml->createElement('id' , 'bundleid');
$title = $root->appendChild($title);
$xml->formatOutput = true;
$xml_string = $xml->saveXML();
// Store XML to file.
file_put_contents('path/myXmlFile.xml',$xml_string);
// Output XML to browser.
//header("Content-type: text/xml");
//echo $xml_string;
Related
I am using PHP to generate a XML and display on my browser. I have the following code:
<?php
header("content-type:application/xml; charset=ISO-8859-15");
$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;
$doc->preserveWhiteSpace = false;
$root = $doc->createElement('book');
$root = $doc->appendChild($root);
$title = $doc->createElement('title');
$title = $root->appendChild($title);
$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);
//echo "Saving all the document:\n";
//echo $doc->saveXML()."\n";
echo "Saving only the title part:\n";
echo $doc->saveXML($title);
?>
If I comment out echo "Saving only the title part:\n";, it generates the XML to me in my browser without any problem, but if I try to add this echo "Saving only the title part:\n"; before echo $doc->saveXML($title);, it will give me the following error in my browser :
This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.
Does anybody knows why? Is there a way to display a string before printing out the XML in my browser?
This is because you have set your documents content type to application/xml, so the browser is expecting all content to be in the form of XML.
To get the above code to work, change the content type to text/plain
The following code works (tested on my machine):
header("content-type:text/plain; charset=ISO-8859-15");
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$doc->preserveWhiteSpace = false;
$root = $doc->createElement('book');
$root = $doc->appendChild($root);
$title = $doc->createElement('title');
$title = $root->appendChild($title);
echo "Saving only the title part:\n";
echo $doc->saveXML($title);
Im trying to create a XML file using php.
When I print my xml it prints it all in one line and not in proper format.
$xml = new DomDocument();
**$xml->preserveWhiteSpace = false;
$xml->FormatOutput = true;**
$parent = $xml->createElement("foo");
$parent->setAttribute("xmlns", "http://");
$parent->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
$parent->setAttribute("xsi:schemaLocation", "link");
$xml->appendChild($parent);
$child = $xml->createElement("foo1");
$parent->appendChild($child);
$subchile = $xml->createElement($foo);
$child->appendChild($subchile);
$s_c = $xml->createElement("foo3",$foo3);
$subchile->appendChild($s_c);
echo "<xmp>" . $xml->saveXML() . "<xml>";
$xml->save($file_name)
it prints everything without indentations etc.
I read other questions here and followed the answers but still nothing. Can you help?
changed $xml->FormatOutput = true; ---> $xml->formatOutput = true;
I'm simply wanting to add cdata to an xml node - description. My xml function is below. I have tried using bits of the following function on php.net in my function
<?php
function updateXMLFile($itemName, $description, $pageName, $imageFileName)
{
$imageSrc = "<img src='http://nicolaelvin.com/authoring/phpThumb/phpThumb.php?src=../images/" . $imageFileName . "&w=100'/>";
$id = strtolower($id = str_replace(' ', '_', $itemName));
$directLinkToItem = 'http://nicolaelvin.com/authoring/' . $pageName . '.php#' . $id;
$xml = simplexml_load_file('nicolaElvinsPortfolio.xml');
$item = $xml->channel->addChild('item');
$item->addChild('title', $itemName);
$item->addChild('pubDate', date('r'));
$item->addChild('link', $directLinkToItem);
$item->addChild('description');
$cdata->description->createCDATASection('testyfhgjhsgsdjahgs');
$item->appendChild($cdata);
///Format XML to save indented tree rather than one line
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
//Save XML to file - remove this and following line if save not desired
$dom->save('nicolaElvinsPortfolio.xml');
}
//function from php.net
function sxml_cdata($path, $string)
{
$dom = dom_import_simplexml($path);
$cdata = $dom->ownerDocument->createCDATASection($string);
$dom->appendChild($cdata);
}
?>
Try this on for size. Let me know if you have any problems with it/questions about it (FIXED).
function updateXMLFile($itemName, $description, $pageName, $imageFileName) {
// Path to file that will be used
$filePath = 'nicolaElvinsPortfolio.xml';
// Create links - don't forget to escape values appropriately with urlencode(), htmlspecialchars() etc
$imageSrc = "<img src='".htmlspecialchars('http://nicolaelvin.com/authoring/phpThumb/phpThumb.php?src=../images/'.urlencode($imageFileName).'&w=100')."'/>";
$directLinkToItem = 'http://nicolaelvin.com/authoring/'.urlencode($pageName).'.php#'.urlencode(strtolower(str_replace(' ', '_', $itemName)));
// Create the CDATA value - whatever you want this to look like
$cdata = "$description: $imageSrc";
// Create a DOMDocument
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
// Load data from file into DOMDocument
if (!$dom->load($filePath)) throw new Exception("Unable to load data source file '$filePath'");
// Create the new <item> and add it to the document
$item = $dom->getElementsByTagName('channel')->item(0)->appendChild(new DOMElement('item'));
// Add the <item>'s sub elements
$item->appendChild(new DOMElement('title', $itemName));
$item->appendChild(new DOMElement('pubDate', date('r')));
$item->appendChild(new DOMElement('link', $directLinkToItem));
// Add the CDATA
$item->appendChild(new DOMElement('description'))->appendChild(new DOMCdataSection($cdata));
// Now save back to file
$dom->save($filePath);
}
N.B. this now throws an exception if DOMDocument::load() fails - don't forget to catch it!
I'm trying to print complex XML's node values using XPath, I have attached an image for helping to see the path which I need to reach (red underline).
Original XML file can be found here
I was trying something like that:
<?php
$xml = simplexml_load_file('document.xml');
echo "<strong>Using direct method...</strong><br />";
$names = $xml->xpath('/w:document/w:body/w:tbl[0]/w:tr[1]/w:tc[0]/w:p/w:r/w:t');
foreach($names as $name) {
echo "Found $name<br />";
}
?>
This method I am using to replace this node:
$file = "document.xml";
$fp = fopen($file, "rb") or die("error");
$str = fread($fp, filesize($file));
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error");
$root = $xml->documentElement;
$fnode = $root->childNodes->item(0);
$ori = $fnode->childNodes->item(1);
$ori1 = $ori->childNodes->item(3);
$ori2 = $ori1->childNodes->item(1);
$ori3 = $ori2->childNodes->item(1);
$ori4 = $ori3->childNodes->item(1);
$ori5 = $ori4->childNodes->item(1);
$wt = $xml->createElement("w:t");
$wtText = $xml->createTextNode("".$name." ".$item."");
$wt->appendChild($wtText);
$ori4->replaceChild($wt,$ori5);
$xml->save("document.xml");
<?php
// Load XML
$doc = new DOMDocument();
$doc->load("document.xml");
// Use xpath to grab the node in question. I copied your xpath
// query as-is, assuming it was capable of targetting exactly
// the node you are trying to replace. If it returns more than
// one node, then only the first will be replaced.
// If this isn't what you want, I suggest modifying your xpath
// query to match exactly the single node you want to replace.
$xpath = new DOMXPath($doc);
$oldElement = $xpath->query("/w:document/w:body/w:tbl[0]/w:tr[1]/w:tc[0]/w:p/w:r/w:t")->item(0);
$newElement = $doc->createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t", $name . " " . $item);
// Replace old element with new element
$oldElement->parentNode->replaceChild($newElement, $oldElement);
?>
The below code is fetched from php.net (http://docs.php.net/manual/en/domdocument.savexml.php). My problem is - it doesn't work. My only output from this is: "Saving all the document: Saving only the title part:". What am I missing here?
$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;
$root = $doc->createElement('book');
$root = $doc->appendChild($root);
$title = $doc->createElement('title');
$title = $root->appendChild($title);
$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);
echo "Saving all the document:\n";
echo $doc->saveXML() . "\n";
echo "Saving only the title part:\n";
echo $doc->saveXML($title);
PHP sends a Content-type http header. And by default it's text/html. I.e. the client is supposed to interpret the response document as html. But you're sending an xml document (and some text and another fragment, which invalidates the output).
If you want to send an xml document tell the client so, e.g. via header('Content-type: text/xml')
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->appendChild($doc->createElement('book'));
$title = $root->appendChild($doc->createElement('title', 'This is the title'));
if (headers_sent() ) {
echo 'oh oh, something wnet wrong';
}
else {
header('Content-type: text/xml; charset=utf-8');
echo $doc->saveXML();
}