MSXML2.DOMDocument Object required error if file extension is not .xml - php

Working on an application to retreive shipping rates as XML from a web service. The web service is PHP based. The client is VB Script, specifically HTA.
During initial development I used an XML file on the server as a test. Here is the content of that file:
<shipping>
<rate>
<method>FEDEX GROUND</method>
<description>FedEx Ground</description>
<amount>10.00</amount>
</rate>
<rate>
<method>FEDEX 2 DAY</method>
<description>FedEx 2nd Day</description>
<amount>20.00</amount>
</rate>
<rate>
<method>FEDEX NEXT DAY</method>
<description>FedEx Next Day</description>
<amount>30.00</amount>
</rate>
</shipping>
When I use MSXML2.ServerXMLHTTP to get that file I have no issues using MSXML2.DOMDocument to parse the XML.
If I attempt to get the exact same XML from a PHP script, or even if I copy the XML file to a filename with a non-xml extension, like .txt, I get an Object Required error trying to access the document elements.
When getting the data from PHP I am setting the header like so:
header('Content-Type: application/xml; charset=utf-8');
Here is the VB Script code:
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "GET", "http://craig.clearos.lan/c9pets/api/shippingRates", False
xmlhttp.send
results=xmlhttp.ResponseText
Set xmlDoc = CreateObject("MSXML2.DOMDocument")
xmlDoc.load(xmlhttp.responseXML)
Set ratesNodeCollection = xmlDoc.DocumentElement.getElementsByTagName("rate")
This errors out on the last line with "Object required: 'xmlDoc.DocumentElement'"
If I change line 2 to this
'xmlhttp.open "GET", "http://craig.clearos.lan/sage/hello.xml", False
it works as expected.
Again, I have verified that the PHP code and the .txt file contain the exact same XML as the .xml file.
I have added parseError trapping and I'm getting the message "XML document must have a top level element." This makes no sense to me. There is a top level element named I've also added to the .xml file and the output of PHP. This did not change anything. I tried setting the header to text/xml instead of application/xml, which also did nothing.
For reference here is the very simple php code that builds the XML.
$shipping=array(0=>array('method'=>'FEDEX GROUND', 'description'=>'FedEx Ground', 'amount'=>'10.00'),
1=>array('method'=>'FEDEX 2 DAY', 'description'=>'FedEx 2nd Day', 'amount'=>'20.00'),
2=>array('method'=>'FEDEX NEXT DAY', 'description'=>'FedEx Next Day', 'amount'=>'30.00'));
$xml=new SimpleXMLElement('<shipping/>');
foreach($shipping as $row){
$rate=$xml->addChild('rate');
$rate->addChild('method', $row['method']);
$rate->addChild('description', $row['description']);
$rate->addChild('amount', $row['amount']);
}
Header('Content-type: application/xml');
print($retVal->asXML());

Related

XML Error: Invalid character

I have the below php code that is parsing xml from url
$parser=xml_parser_create();
function char($parser,$data)
{
echo $data;
}
xml_set_character_data_handler($parser,"char");
$fp=fopen("http://example.com","r");
while ($data=fread($fp,4096))
{
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
The xml returned by above fopen call is like this.The Xml don't have any encoding set at top.
The above code is outputing XML Error: Invalid character at line 1008 on browser.
<entries> //root element
<entry>
<TITLE><![CDATA[xxxx yyyyyyyyyy]]></TITLE>
</entry>
<entry>
<TITLE><![CDATA[xxxx Gold… yyyyyyyyyy]]></TITLE>//this is line no 1008 that returns invalid character error and script stops
</entry>
</entries>
I think it might be due to ellipses because When I save the xml returned in local file in notepad++ and then feed that xml file the above parser runs good.
I want to run this xml directly from url instead of saving it into directory because that will be a overhead I don't need.Thanks
Make sure the web server you're pulling the file from is sending the correct character encoding when it serves the page. You should see something like this in the response headers:
Content-Type:"text/xml; charset=utf-8"
The headers can be viewed in the network panel of the inspector in any modern browser, when you request the XML file directly.
You should also specify the encoding in the file itself. The first line should look something like this:
<?xml encoding='UTF-8'?>
If these fail, you can always try using utf8_decode() which is an XML_Parser function that will attempt to convert the data to iso-8859-1.

Importing PHP file in Flash doesn't work

I'm extracting data from MySQL into flash. First I use PHP to query the DB, and then I echo the results.
$sql = "SELECT path FROM video WHERE id = 52";
$resource = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($resource);
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<video>\n";
echo "<path>" . $row['path'] . "</path>\n";
echo "</video>\n";
I only have one root element, and I don't see anything wrong with my markup following the root element...but then again I'm wrong and I'm sure there is an error.
--- Changed my Title so I added the error message here ---
TypeError: Error #1088: The markup in the document following the root element must be well-formed.
------EDITED ------
The value of $row['path'] is a string from my DB. I know it's valid because I deleted all xml tags and echoed $row['path'] which is the url path for the video. I also used gettype(), and it outputs a string.
When I open this file into my browser, I actually don't see anything. It's a blank page, but it's because the browser is rendering it as html elements, so I don't think that's the problem. But when I view source, I get this
<?xml version="1.0" encoding="UTF-8"?>
<video>
<path>1.mp4</path>
</video>
In addition, I created a random file with an xml extension with the xml contents above, (copied it form View Source that my php file outputs) and it works fine. I see the contents in Flash. What could be wrong with echoing it out in a php file? I'm using textWrangler. It might have something to do with BOM, any suggestions?
----EDIT NUMBER TWO ---
Here's my actionscript code. I'm still new so I didn't put it in a class but inside the first frame in my actions layer. I'm just trying to get the basics to work.
var theXML:XML;
var xmlReq:URLRequest = new URLRequest("../folderExample/poop.php");
var xmlLoader:URLLoader = new URLLoader();
function xmlLoaded(event:Event):void{
theXML = new XML(xmlLoader.data); // The Error occurs here.
trace(theXML.toXMLString());
}
xmlLoader.load(xmlReq);
xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
From http://www.flashdevelop.org/community/viewtopic.php?f=13&t=3128
For well-formed XML returning
TypeError: Error #1088: The markup in the document following the root element must be well-formed,
often the problem is the BOM.
Actionscript XML does not strip the BOM (Byte Order Mark) from incoming text. The BOM is an invisible character (#65279) created at the beginning of a ASP or php "echo" string, as well as some text editors, to indicate the byte-ordering of multibyte text.
You can confirm if your string has this BOM character like this:
trace( sXMLString.charCodeAt( 0 ) ); //outputs 65279
The quick solution is
sXMLString= sXMLString.replace( String.fromCharCode(65279), "" ) ;
myXML = new XML(sXMLString);
See also:
Reading php generated XML in flash?
How to load PHP dynamically generated XML in FLASH
If you don't have it already, from the second link above, try adding:
header("Content-Type: text/xml");

How to Download XML File from a web service with HTML like code

I am new to PHP. I am downloading an XML file from a web service using PHP. I can download the file using this code:
$sourcefile = "http...com?querystring=string";
$destinationfile = 'data\description.xml';
$xml = file_get_contents($sourcefile);
file_put_contents($destinationfile, $xml);
But when I open the XML file, it has < where < should be and > where > should be.
I added this line of code to decode it before saving it to file, which fixes the above problem:
$xml = html_entity_decode($xml);
This doesn't seem to me to be the right way to go about it. Also, I am getting a weird piece of text showing up in the XML file, which prevents me from parsing the XML file:

I tried using str_replace($xml) right before decoding it (and tried it after decoding it), but that wouldn't get rid of it.
What is the correct way to download an XML file using GET from a web service in PHP and will it get rid of that weird string ()?

PHP Print Included XML File

I'm trying to echo out an XML File via a PHP File. Like so:
Url visits viewxml.php?id=1
Php open a specific XML file, such as "xmlfile_".$_GET['id'].".xml" and prints it as if they are visiting the xml file itself.
The reason I'm using PHP is to do Session checks to make sure they are allowed to view the xml file.
This is how I am doing this:
header("Content-type: text/xml; charset=utf-8");
// send the saved XML file.
include "xmlfile_".$id.".xml";
Doing this gives me the following GC XML error:
And there is nothing below it.
I have tried different approaches, such as printing it or turning it into a string but then I have problems reading the XML on certain software. I am hoping one of you can help me.
Thanks!
include() will attempt to evaluate the file; if there's something in there that looks like PHP then it will corrupt your results.
Try using readfile instead; this will only output the file contents.

What file extension should I use for dynamic RSS

I am currently developing a dynamic RSS feed that will automatically pull articles from a MySQL database. The code is below
<?php
//Include the post retreival script
require_once '../phpScripts/rss_db_setup.php';
//Set the content type
header('Content-type: text/xml');
//Set up the RSS feed information
echo '<?xml version="1.0" encoding="ISO-8859-1"?>'.
'<rss version="2.0">'.
'<channel>'.
'<title>Company Name</title>'.
'<link>http://www.company.ca</link>'.
'<description></description>'.
'<category></category>';
//Retreive posts from the database
$rssData = new rssData();
echo $rssData->generateFeed($dbcon);
//Close the feed
echo '</channel></rss>';
?>
I am wondering whether this file should be saved as a .xml or a .php? I have added the following line to my .htaccess file, but do not really understand exactly how it works
AddType application/x-httpd-php .xml
Is this a correct way to do this? Or should I use another htaccess function such as modRewrite, or use a CRON job to generate a new .xml every day or so?
RSS doesn't need a extension. It doesn't care if the url is /feed.php /feed.xml or even just /feed/. It's not like the files on your own harddrive. HTTP send the content-type header to specify what kind of file it is.
It however (officially) needs the correct content-type header. You specify text/xml in your code, which should officially be application/rss+xml.
Using AddType could be a problem if you use static xml files elsewhere on the server. PHP would choke on the part at the beginning of every xml file, give a nice error message resulting in invalid xml.
With the AddType application/x-httpd-php .xml line, Apache will be able to serve XML files containing some PHP code inside. So you can save this file as a .xml, the PHP code will be interpreted
Perhaps you should add a cache manager in order to avoid generating the same feed when there is no new article?

Categories