从PHP文件中的网站获取XML数据(内部服务器错误)

时间:2014-10-17 22:27:49

标签: php ajax xml internal-server-error

我需要使用API​​密钥从网站获取XML数据,并且我使用AJAX和PHP。 这是我的AJAX代码(顺便说一句,PHP文件在FileZilla服务器中):

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

这是PHP代码:

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

我从浏览器控制台收到此错误: 获取http://phpdev2.dei.isep.ipp.pt/~i110815/recebeXml.php 500(内部服务器错误) 谁知道什么是错的?

1 个答案:

答案 0 :(得分:1)

内部服务器错误只是500 HTTP Status Code的通用名称:

  

500内部服务器错误      一个通用错误消息,在遇到意外情况时给出,并且没有更合适的消息。

您必须check your webserver's error log才能找到有关实际错误的详细信息。

根据您显示的代码示例判断,错误可能是由于此部分

$newXML->loadXML($respostaXML); 
echo $newXML;

您的$newXMLDOMDocument instance。它没有实现__toString所以它不能以这种方式回应。你必须使用

换句话说:

$newXML->loadXML($respostaXML); 
echo $newXML->saveXml();

请参阅我对DOMDocument in php

的介绍

旁注:如果您只想从远程API获取XML然后输出XML,那么将XML加载到DOM中是没有意义的。只需执行readfile而不是file_get_contents,并在通话后删除所有内容。

如果这不能解决错误,我认为您的服务器已禁用allow_url_fopen,并且您无法向远程网址发出请求。 You need to find another way of downloading the XML then.

相关问题