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

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); ?>

Related

I am getting unexpected <head/> in my xml file how to remove that tag

I am generating an api for trip advisor but while sending the xml file an unexpected tag i am getting in production.but i am not getting in localhost.
i have generated xml file using DOM document.
here a copy of my code.
$data=$this->property_model->getreservations_data($start_date,$end_date);
$xml= new DOMDocument("1.0","UTF-8");
$xml->FormatOutput=true;
$Reservations=$xml->createElement('Reservations');
$Reservations=$xml->appendChild($Reservations);
foreach ($data as $key) {
$Reservation=$xml->createElement('Reservation');
$Reservation->setAttribute('property_id',$key['prop_id']);
$Reservation->setAttribute('reservation_id',$key['booking_id']);
$Reservation=$Reservations->appendChild($Reservation);
$EmailAddress=$xml->createElement('EmailAddress',$key['email']);
$EmailAddress=$Reservation->appendChild($EmailAddress);
$fromdate=date('Y-m-d',strtotime($key['travel_from_date']));
$ArrivalDate=$xml->createElement('ArrivalDate',$fromdate);
$ArrivalDate=$Reservation->appendChild($ArrivalDate);
$todate=date('Y-m-d',strtotime($key['travel_to_date']));
$DepartureDate=$xml->createElement('DepartureDate',$todate);
$DepartureDate=$Reservation->appendChild($DepartureDate);
if ($key['order_status']=='Success') {
$Status=$xml->createElement('Status');
$Status->setAttribute('value','reserved');
$Status=$Reservation->appendChild($Status);
}else{
$Status=$xml->createElement('Status');
$Status->setAttribute('value','cancelled');
$Status=$Reservation->appendChild($Status);
}
}
echo $xml->saveXML();
}
output in production:
<?xml version="1.0" encoding="UTF-8"?>
<head/><Reservations><Reservation property_id="998" reservation_id="1998"><EmailAddress>kunal31393#gmail.com</EmailAddress><ArrivalDate>2015-12-07</ArrivalDate><DepartureDate>2018-05-06</DepartureDate><Status value="reserved"/>
output in localhost:
<?xml version="1.0" encoding="UTF-8"?>
<Reservations><Reservation property_id="290" reservation_id="10292"><EmailAddress>yogeshb#gmail.com</EmailAddress><ArrivalDate>2016-10-20</ArrivalDate><DepartureDate>2017-05-17</DepartureDate><Status value="reserved"/>
you need to try sending xml with proper content type
set
header("Content-Type: application/xml");

Formatting SimpleXMLElement

According to this answer it is possible to echo out formatted xml. Yet this php code:
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><data></data>");
$xml->addChild("child1", "value1");
$xml->addChild("child2", "value2");
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
echo $dom->saveXML();
outputs value1 value2
So how do I format it correctly nowadays?
To echo out formatted XML (or HTML) you have to use htmlentities built-in function, that “convert all applicable characters to HTML entities”.
In your case:
echo htmlentities($dom->saveXML());
will output this:
<?xml version="1.0" encoding="utf-8"?> <data> <child1>value1</child1> <child2>value2</child2> </data>
Using-it together with <pre> html tag, also newlines and spaces will be printed:
echo '<pre>' . htmlentities($dom->saveXML()) . '</pre>';
will output this:
<?xml version="1.0" encoding="utf-8"?>
<data>
<child1>value1</child1>
<child2>value2</child2>
</data>

PHP - Parse, Read XML

Not too sure what I'm doing wrong with parsing/reading an xml document.
My guess is that it's not standardized, and I'm going to need a different process to read anything from the string.
If that's the case, then I'm rather excited to learn how someone would read the xml.
Here's what I've got, and what I'm doing.
example.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="someurl.php"?>
<response>
<status>Error</status>
<error>The error message I need to extract, if the status says Error</error>
</response>
read_xml.php
<?php
$content = 'example.xml';
$string = file_get_contents($content);
$xml = simplexml_load_string($string);
print_r($xml);
?>
I'm getting no result back from the print_r.
I switched the xml to something more standard, like:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
...and it worked fine. So I'm sure it's due to a non-standard format, passed back from the source I'm getting it from.
How would I extract the <status> and <error> tags?
Tek has a good answer, but if you want to use SimpleXML, you can try something like this:
<?php
$xml = simplexml_load_file('example.xml');
echo $xml->asXML(); // this will print the whole string
echo $xml->status; // print status
echo $xml->error; // print error
?>
EDIT: If you have multiple <status> and <error> tags in your XML, have a look at this:
$xml = simplexml_load_file('example.xml');
foreach($xml->status as $status){
echo $status;
}
foreach($xml->error as $error){
echo $error;
}
I'm assuming <response> is your root. If it isn't, try $xml->response->status and $xml->response->error.
I prefer to use PHP's DOMDocument class better.
Try something like this:
<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="someurl.php"?>
<response>
<status>Error</status>
<error>The error message I need to extract, if the status says Error</error>
</response>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$statuses = $dom->getElementsByTagName('status');
foreach ($statuses as $status) {
echo "The status tag says: " . $status->nodeValue, PHP_EOL;
}
?>
Demo: http://codepad.viper-7.com/mID6Hp

XML Encoding generated from 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).

PHP Flickr API - Retrieve Title from flickr.photosets.getInfo Response

I am getting the correct response from Flickr which is:
<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<photoset id="72157630469695108" owner="15823425#N00" primary="5110549866" secret="fd716fb5ee" server="1136" farm="2" photos="101" count_views="67" count_comments="0" count_photos="101" count_videos="0" can_comment="0" date_create="1341701808" date_update="1345054078">
<title>Montana</title>
<description />
</photoset>
</rsp>
For some reason I can't get the title, I've tried the following:
$album_info = simplexml_load_file($album_info_xml); // this is what the response is stored in
echo $album_info['photoset']['title'];
foreach($album_info->photoset as $ps) {
echo $ps['title'];
}
And a couple of other crazy things, I know it's something silly but don't know what it is I have missed.
Response can be seen here: http://www.flickr.com/services/api/explore/flickr.photosets.getInfo
Just use 72157630469695108 as the set id or alternatively use this url: http://api.flickr.com/services/rest/?method=flickr.photosets.getInfo&api_key=7ccedd2c89ca10303394b8085541d9de&photoset_id=72157630469695108
You should use SimpleXMLElement directly, then xpath to find your node.
$album_info = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<photoset id="72157630469695108" owner="15823425#N00" primary="5110549866" secret="fd716fb5ee" server="1136" farm="2" photos="101" count_views="67" count_comments="0" count_photos="101" count_videos="0" can_comment="1" date_create="1341701808" date_update="1345054078">
<title>Montana</title>
<description />
</photoset>
</rsp>'); // this is what the response is stored in
$result = $album_info->xpath('//title');
foreach ($result as $title)
{
echo $title . "\n";
}
Working example.
For anyone in the same position, this did the trick
$albumName = $album_info->photoset->title;

Categories