XML Encoding generated from PHP - php

I am doing an assignment for class where I have to use a Java Servlet running on Tomcat and have it message a php file to scrape IMDB for movie information and return it as XML to the servlet. It seems to not want to accept any encoding I give it as I continuously get XML tags such as the ones below.
<result cover="url" title="Pokémon" year="1998 TV Series" director="N/A" rating="7.8" details="http://www.imdb.com/title/tt0176385/"/>
Where title of Pokemon should have an accent over the e («é»). I have the following php code to generate the xml. (Important parts only)
<?php header("Content-Type: text/xml; charset=utf-8");
$xml = new DOMDocument();
$rsp = $xml->appendChild($xml->createElement("rsp"));
$xml->encoding = 'utf-8';
$titleNames[$i] = utf8_encode($title_tmp[1]);
$results = $rsp->appendChild($xml->createElement("results"));
$results->setAttribute("total", $tableRows);
$item->setAttribute("title", $titleNames[$i]);
echo $xml->saveXML();
?>
Any help would be greatly appreciated in figuring out how to correctly display special characters!

It's impossible to say what's wrong from your code fragments (which don't even run) but $xml->encoding = 'utf-8' should work. Please compare:
$xml = new DOMDocument();
$rsp = $xml->appendChild($xml->createElement("rsp"));
$rsp->setAttribute("title", 'Pokémon');
echo $xml->saveXML();
/*
<?xml version="1.0"?>
<rsp title="Pokémon"/>
*/
... with:
$xml = new DOMDocument();
$xml->encoding = 'utf-8';
$rsp = $xml->appendChild($xml->createElement("rsp"));
$rsp->setAttribute("title", 'Pokémon');
echo $xml->saveXML();
/*
<?xml version="1.0" encoding="utf-8"?>
<rsp title="Pokémon"/>
*/
(These snippets are expected to be saved as UTF-8).

Related

Xml error This page contains the following errors:

php code creates xml and displays on screen. Unfortunately, I get an error and I don't know how to fix it.
This page contains the following errors:
error on line 2 at column 1: Extra content at the end of the document
Below is a rendering of the page up to the first error.
The structure of the xml file itself looks good after saving
<Movies>
<movie movie_id="5467">
<Title>The Campaign</Title>
<Year>2012</Year>
<Genre>The Campaign</Genre>
<Ratings>6.2</Ratings>
</movie>
</Movies>
I need to display the same code on screen after calling php.
$dom = new DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$xml_file_name = 'movies_list.xml';
$root = $dom->createElement('Movies');
$movie_node = $dom->createElement('movie');
$attr_movie_id = new DOMAttr('movie_id', '5467');
$movie_node->setAttributeNode($attr_movie_id);
$child_node_title = $dom->createElement('Title', '<![CDATA[The Campaign]]');
$movie_node->appendChild($child_node_title);
$child_node_year = $dom->createElement('Year', 2012);
$movie_node->appendChild($child_node_year);
$child_node_genre = $dom->createElement('Genre', '<![CDATA[The Campaign]]');
$movie_node->appendChild($child_node_genre);
$child_node_ratings = $dom->createElement('Ratings', 6.2);
$movie_node->appendChild($child_node_ratings);
$root->appendChild($movie_node);
$dom->appendChild($root);
Header('Content-type: text/xml');
echo $xml_file_name->asXML();
Please help me in solving. I looked for many solutions but nothing helped.

PHP - Format XML Output

I'm generating some XML data in response to an HTTP POST request. I'm setting the MIME
header('Content-type: text/xml');
and everything is working well so far.
I'm generating the xml response as follows:
$response = '<?xml version="1.0" encoding="utf-8"?>';
$response .= '<error>';
$response .= '<description>'.$error.'</description>';
$response .= '</error>';
echo $response;
I would now like the format the XML so that instead of seeing this response:
<?xml version="1.0" encoding="utf-8"?><error><description>Login Error: No Username Supplied</description></error>
they see this response:
<?xml version="1.0" encoding="utf-8"?>
<error>
<description>Login Error: No Username Supplied</description>
</error>
I haven't worked with XML output with PHP before so not sure if there's a built in method for doing a "pretty print" type function on the output?
Use the DOM library and set the formatOutput property to true
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElement('error');
$doc->appendChild($root);
$desc = $doc->createElement('description', $error);
$root->appendChild($desc);
echo $doc->saveXML();
Demo ~ https://eval.in/461384

Generate XML using PHP

I have the following PHP code from which I need to generate XML.
$hparams["SiteName"]="";
$hparams["AccountCode"]="";
$hparams["UserName"]='xxxx';
$hparams["Password"]='xxxx';
$client_header = new SoapHeader('url','AuthenticationData',$hparams,false);
$cliente = new SoapClient($wsdl); $cliente->__setSoapHeaders(array($client_header));
$opta=array();
$opta["Search"]["request"]["Origin"]="MAA";
$opta["Search"]["request"]["Destination"]="BOM";
$opta["Search"]["request"]["DepartureDate"]="2014-05-20T00:00:00";
$opta["Search"]["request"]["ReturnDate"]="2014-05-22T00:00:00";
$opta["Search"]["request"]["Type"]="OneWay";
$opta["Search"]["request"]["CabinClass"]="All";
$opta["Search"]["request"]["PreferredCarrier"]="";
$opta["Search"]["request"]["AdultCount"]="1";
$opta["Search"]["request"]["ChildCount"]="0";
$opta["Search"]["request"]["InfantCount"]="0";
$opta["Search"]["request"]["SeniorCount"]="0";
$opta["Search"]["request"]["IsDirectFlight"]="true";
$opta["Search"]["request"]["PromotionalPlanType"]="Normal";
$h=array();
$h= (array)$cliente->__call('Search',$opta);
How can I generate an XML of the above variables in PHP ?
The format should be
<xml>
<credential>
<Sitename>sitename</Sitename>
<AccountCode>ACC Code</AccountCode>
</credentials>
<Data>
<Origin>MAA</Origin>
<Destination>BOM</Destination>
</Data>
</xml>
Any help would be appreciate.
Thank you.
<?php
ini_set('error_reporting', E_ALL);
$dom = new DomDocument('1.0'); // making xml
$credentials = $dom->appendChild($dom->createElement('Credentials')); // adding root element <credentials>
$sitename = $credentials->appendChild($dom->createElement('Sitename')); // adding element <sitename> in <credentials>
$accountcode = $credentials->appendChild($dom->createElement('AccountCode')); // adding element <accountcode> in <credentials>
$sitename->appendChild($dom->createTextNode('sitename')); // adding text in <sitename>
$accountcode->appendChild($dom->createTextNode('ACC Code')); // adding text in <accountcode>
$data = $dom->appendChild($dom->createElement('Data'));
$origin = $data->appendChild($dom->createElement('Origin'));
$destination = $data->appendChild($dom->createElement('Destination'));
$origin->appendChild($dom->createTextNode('MAA'));
$destination->appendChild($dom->createTextNode('BOM'));
$dom->formatOutput = true; // generating xml
// generating XML as string or file
$test1 = $dom->saveXML();
$dom->save('test1.xml');
?>
I think you could write loop by yourself ;)
P.S. PHP 5+
First of all, your xml is not well structured.
It should be like:
<xml>
<credentials>
<Sitename>sitename</Sitename>
<AccountCode>ACC Code</AccountCode>
<Data>
<Origin>MAA</Origin>
<Destination>BOM</Destination>
</Data>
</credentials>
<credentials>
...
</credentials>
</xml>
Iterate the obtained result, and by concating , form the needed xml.

Why can't I embed php in the xml file? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Escaping <? on php shorthand enabled server when using require
What I want is that when I make a Ajax get request to domain/xml.php. It return a XML file, so I can use httpRequest.responseXML to parse the XML file.
what I did is:
<?php
$name = 'Just a tester';
?>
<?xml version='1.0' ?>
<name><?php echo $name ?></name>
But the parser gives me an error of the line <?xml version='1.0' ?>, I thought it might be syntax conflict with the php delimiter <?php.
How can I request a url and get xml generated by php?
You have shorttags enabled. This is the default, and as of PHP 5.4, tags are supported everywhere, regardless of shorttags settings.
The problem is that <?xml version='1.0' ?> starts and ends with <? ?>, just like PHP with shorttags.
To get round this use:
echo "<?xml version='1.0' ?>";
on that line.
Why are you trying to embed PHP variables into XML instead of generating the XML with PHP?
Example (xml.php):
<?php
header('Content-type: text/xml; charset=utf-8');
//Your Data
$persons = array(array('name'=>'bob','age'=>20,'sex'=>'M'),
array('name'=>'steve','age'=>26,'sex'=>'M'),
array('name'=>'jen','age'=>33,'sex'=>'F'),
);
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><persons/>');
foreach ($persons as $person) {
$node = $xml->addChild('person');
foreach($person as $key=>$value){
$node->addChild($key, $value);
}
}
//DOMDocument to format code output
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
echo $dom->saveXML();
/* OUTPUT
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>
<name>bob</name>
<age>20</age>
<sex>M</sex>
</person>
<person>
<name>steve</name>
<age>26</age>
<sex>M</sex>
</person>
<person>
<name>jen</name>
<age>33</age>
<sex>F</sex>
</person>
</persons>
*/
?>
You could try:
<?php
header('Content-type: text/xml; charset=utf-8');
$name = 'Just a tester';
echo "<?xml version='1.0' ?>";
?>
<name><?php echo $name; ?></name>
Change
echo "<?xml...?>";
to
echo '<'."?...?".'>';
Or use Lawerence solution
You should set up your webserver to process not only PHP but XML files also through the PHP preprocessor.
You have short tags enabled. These should be disabled in your php.ini, search for "short_open_tag" and "asp_tag".
If you have an earlier version than PHP 5.3.0 this will probably work (if you only want this for the current document):
<?php ini_set('short_open_tag', 0); ?>

Add XML header information after transform

I have an xml document which I transform, view in the browser and save to a directory.
I would like to add a linked stylesheet to the saved version of the file. I've tried str_replace as below (might be incorrect usage) and also using xsl processing instruction.
xsl processing instruction worked to a degree, if you view source in the browser, you would see the stylesheet link, however it would not save this information to the saved file!!
All I want to do is take the raw xml file, transform it with the stylesheet, save it to a directory and append the xsl stylesheet to the header of the new file, so when the newly saved xml file is opened in the browser, the stylesheet is applied automatically. Hope this makes sense!!
My code is below.
//write to the file
$id = $_POST['id'];//xml id
$path = 'xml/';//send to xml directory
$filename = $path. $id . ".xml";
$header = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '<?xml version="1.0" encoding="UTF-8" ?><?xml-stylesheet type="text/xsl" href="../foo.xsl"?>');
$article->asXML($filename);//saving the original xml as new file with posted id
$xml = new DOMDocument;
$xml->load($filename);
$xsl = new DOMDocument;
$xsl->load('insert.xsl');
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
echo $proc->transformToXML($xml);
Thanks in advance!
You could use the <xsl:processing-instruction/> tag in the XSLT-file to add the stylesheet link.
<xsl:processing-instruction name="xml-stylesheet">
type="text/xsl" href="../foo.xsl"
</xsl:processing-instruction>
This would produce:
<?xml-stylesheet type="text/xsl" href="../foo.xsl"?>
Alternativly, you could do it with a DOMDocument.
$newXml = $proc->transformToXML($xml);
// Re-create the DOMDocument with the new XML
$xml = new DOMDocument;
$xml->loadXML($newXml);
// Find insertion-point
$insertBefore = $xml->firstChild;
foreach($xml->childNodes as $node)
{
if ($node->nodeType == XML_ELEMENT_NODE)
{
$inertBefore = $node;
break;
}
}
// Create and insert the processing instruction
$pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="../foo.xsl"');
$xml->insertBefore($pi, $insertBefore);
echo $xml->saveXML();

Categories