Reputation: 1047
I need to get XML data from a website using an API key, and I'm using AJAX and PHP. Here's my AJAX code (btw, the PHP file is inside a FileZilla server):
var xmlHttpObj=null;
var isPostBack=false;
function CreateXmlHttpRequestObject( )
{
if (window.XMLHttpRequest)
{
xmlHttpObj=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
xmlHttpObj=new ActiveXObject("Microsoft.XMLHTTP")
}
return xmlHttpObj;
}
function MakeHTTPCall_Tags()
{
var link = "http://phpdev2.dei.isep.ipp.pt/~i110815/recebeXml.php";
xmlHttpObj = CreateXmlHttpRequestObject();
xmlHttpObj.open("GET", link, true);
xmlHttpObj.onreadystatechange = stateHandler_Tags;
xmlHttpObj.send();
}
function stateHandler_Tags()
{
if ( xmlHttpObj.readyState == 4 && xmlHttpObj.status == 200)
{
var selectTags = document.getElementById("tag");
var option;
var docxml = xmlHttpObj.responseXML;
var nodelist = docxml.getElementById("name");
alert(nodelist.length);
}
}
Here's the PHP code:
<?php
header("Access-Control-Allow-Origin: * ");
// pedido ao last.fm com a função file_gets_contents
// a string XML devolvida pelo servidor last.fm fica armazenada na variável $respostaXML
$respostaXML=
file_get_contents("http://ws.audioscrobbler.com/2.0/?method=tag.getTopTags&api_key=4399e62e9929a254f92f5cde4baf8a16");
// criar um objecto DOMDocument e inicializá-lo com a string XML recebida
$newXML= new DOMDocument('1.0', 'ISO-8859-1');
$newXML->loadXML($respostaXML);
echo $newXML;
?>
I'm getting this error from the browser console: GET http://phpdev2.dei.isep.ipp.pt/~i110815/recebeXml.php 500 (Internal Server Error) Anybody knows whats wrong?
Upvotes: 1
Views: 887
Reputation: 316999
Internal Server Error is just the generic name for a 500 HTTP Status Code:
500 Internal Server Error A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
You have to check your webserver's error log to find details about the actual error.
Judging by the code sample you show, the error is likely because of this part
$newXML->loadXML($respostaXML);
echo $newXML;
Your $newXML
is a DOMDocument
instance. It doesn't implement __toString
so it cannot be echoed this way. You have to use
In other words:
$newXML->loadXML($respostaXML);
echo $newXML->saveXml();
See my introduction to DOMDocument in php
On a side note: there is no point in loading the XML into DOM if all you want to do is fetch the XML from the remote API and then output it. Just do a readfile
instead of file_get_contents
and remove everything after the call.
If this doesn't fix the error, I assume your server has allow_url_fopen
disabled and you cannot make requests to remote urls. You need to find another way of downloading the XML then.
Upvotes: 1