我在通过php函数header()设置内容类型时遇到问题;我的完整代码永远不会发送任何输出。只有响应对象才能完成。在每次输出之前,我都会发送标头。根据Accept Header,我设置了一个内容类型并进行正确的输出,它看起来很简单:
switch($aceptHeader){
case 'text/html':
#and some othe stupid acept-headers of the ie
$this->setHeader('Content-Type: text/html; charset=".."');
$this->sendHeaders();
$this->sendDefault();
break;
case 'application/json':
$this->setHeader('Content-Type: application/json');
$this->sendJSON();
break;
case 'application/xml':
$this->setHeader('Content-Type: application/xml');
$this->sendXML();
break;
}
setHeader的方法只填充一个数组,wicht将由foreach循环放入header()中;作用这并不重要,因为我直接尝试过,将其$this->setHeader()
更改为header('Content-Type..');
,得到了相同的结果(稍后)输出只是通过一个小树枝模板对数组的渲染。这是唯一的输出。标题的设置不是问题所在。当我做print_r(header_list());
时,我甚至得到了一个积极的结果。在那里,我看到了我之前设置的那个标题。我在几乎所有浏览器中都看到了相同的响应标头,但并非每个浏览器都有:ie8只在预标记之后的正文中显示了作为字符串的html代码。这就是我使用w3c验证器(和其他工具)测试页面的原因。所有显示相同的结果:
他们没有内容类型标题
我可能犯了什么错?在我设置标题之前会有什么错误吗?-我不做任何疯狂的事情或其他任何事情——设置标题不会有任何麻烦-在请求和响应之间的模型中,我唯一更改的头是http状态,它几乎每次都后跟一个$response-send();
。
在呈现树枝模板时,是否会对标头进行操作?
问题是:什么会干扰header()函数对内容类型标头的设置?
有趣的是:我把下面的代码放在我的index.php 的开头
header('Content-Type: text/html');
echo 'test';
exit;
然后我得到了所有验证工具的绿色测试。标头已发送。
我可以浏览我的整个代码,看看我在哪里松了头,但这可能是一条很长的路。有没有人遇到过同样的问题,或者可以想象我做错了什么?
这只是一个类似的例子。开关块不是问题所在,sendHeader也不是问题所在。因为我整个下午都在不同的情况下直接设置了标题,每次都得到了相同的结果。
我在不同的情况下使用了这些输出开关,每次都很好。我发送json,带有一个头,jQuery的$.ajax()接受它作为json而不是字符串。我为我的RESTful api生成了xml,它运行良好,并以我想要的格式发送数据。只有验证器工具和ie8不喜欢它。我不明白为什么。。。
switch($aceptHeader){
case 'text/html':
#and some othe stupid acept-headers of the ie
$this->setHeader('Content-Type: text/html; charset=".."');
$this->sendHeaders();
$this->sendDefault();
break;
case 'application/json':
$this->setHeader('Content-Type: application/json');
$this->sendJSON();
break;
case 'application/xml':
$this->setHeader('Content-Type: application/xml');
$this->sendXML();
break;
}
忘记了告诉代码何时尝试下一个案例的中断。
我解决了这个问题。
而且。。。
这是一个执行问题。这是一个你看不到的东西,因为我不张贴它。事实上,它是默认路径,我将客户端想要获得的wath作为内容类型发送到该路径。意思是,如果客户端(IE8或验证工具)没有发送接受标头或我发送的空字符串,并且"内容类型:",则表示失败。我可以哭了。grrrrrrrrrr。抱歉。
让你知道我的正确实现(我知道需要一些重构):
$acceptFormat = $this->request->getAcceptFormat();
#do a switch for the type of the output and send the headers before
switch ($acceptFormat ){
case 'text/html':
case 'application/x-www-form-urlencoded':
case 'application/x-ms-application':
case 'application/vnd.wap.xhtml+xml':
case '*/*':
$this->setHeader('content-type: text/html; charset=UTF-8');
$this->_sendHeaders();
$this->_sendDefault();
break;
case 'application/json':
$this->setHeader('Content-Type: application/json');
$this->_sendHeaders();
$this->_sendJSON();
break;
case 'application/xml':
$this->setHeader('Content-Type: application/xml');
$this->_sendHeaders();
$this->_sendXML();
break;
default:
$this->debugger->log('Unknown Accept-Header set: '.$acceptFormat.' for setting the Content-Type ');
#$this->setHeader('content-type: '.$acceptFormat);
$this->setHeader('content-type: text/html; charset=UTF-8');
$this->_sendHeaders();
$this->_sendDefault();
break;
}
被评论的部分是错误。
天啊。。。
但我从来没有想过,浏览器永远不会发送任何接受类型的内容。