Content type для xml php

XML on the Server

XML can easily be stored and generated by a standard web server.

Storing XML Files on the Server

XML files can be stored on an Internet server exactly the same way as HTML files.

Start Windows Notepad and write the following lines:

Save the file on your web server with a proper name like «note.xml».

Generating XML with PHP

XML can be generated on a server without any installed XML software.

To generate an XML response from the server using PHP, use following code:

Note that the content type of the response header must be set to «text/xml».

If you want to study PHP, you will find our PHP tutorial on our homepage.

Generating XML with ASP

To generate an XML response from the server — simply write the following code and save it as an ASP file on the web server:

Note that the content type of the response must be set to «text/xml».

If you want to study ASP, you will find our ASP tutorial on our homepage.

Generating XML From a Database

XML can be generated from a database without any installed XML software.

To generate an XML database response from the server, simply write the following code and save it as an ASP file on the web server:

<%
response.ContentType = «text/xml»
set conn=Server.CreateObject(«ADODB.Connection»)
conn.provider=»Microsoft.Jet.OLEDB.4.0;»
conn.open server.mappath(«/datafolder/database.mdb»)

sql=»select fname,lname from tblGuestBook»
set rs=Conn.Execute(sql)

The example above uses ASP with ADO.

If you want to study ASP and ADO, you will find the tutorials on our homepage.

Transforming XML with XSLT on the Server

This ASP transforms an XML file to XHTML on the server:

<%
‘Load XML
set xml = Server.CreateObject(«Microsoft.XMLDOM»)
xml.async = false
xml.load(Server.MapPath(«simple.xml»))

‘Load XSL
set xsl = Server.CreateObject(«Microsoft.XMLDOM»)
xsl.async = false
xsl.load(Server.MapPath(«simple.xsl»))

‘Transform file
Response.Write(xml.transformNode(xsl))
%>

  • The first block of code creates an instance of the Microsoft XML parser (XMLDOM), and loads the XML file into memory.
  • The second block of code creates another instance of the parser and loads the XSL file into memory.
  • The last line of code transforms the XML document using the XSL document, and sends the result as XHTML to your browser. Nice!
Читайте также:  Знак равенства на питоне

Источник

PHP XML header

PHP XML header

PHP XML header is the XML content type output from PHP file instead of default header content of text/html. Setting the header content type to XML indicates that the output to the browser is in XML format. XML stands for Extensible Markup Language, which denotes rules for document encoding. PHP being an open-source programming language, is used to dynamically set web content and applications at the server end. Similar to how Dynamic HTML content is generated in PHP, dynamic XML content can also be generated in PHP.

Web development, programming languages, Software testing & others

Syntax

Given below is the syntax of the PHP XML header:

Above is the basic syntax of the Content-type to be changed to XML when using PHP XML header.

header(header, replace, http_response_code)

The basic Header function sends raw HTTP header to the client; it is called before the output is sent.

  • header: It specified the header string to be sent and is a mandatory parameter.
  • replace: It indicates if the header should replace the previous header or add a new header of the same type. It is an optional parameter, and the default being TRUE, i.e. will replace. Boolean FALSE allows multiple headers with the same type.
  • http_response_code: It forces HTTP response code to specific value and is an optional parameter.

In PHP, no output can occur before the occurrence of the header() sent to the browser. Content-Type of header tells the browser on how to handle the content. For e.g., If there is a PDF file which the browser can’t support, it will give an option to use other application. It will tell to use other application on our system or will ask to download a particular application.

If the Content-type is text/xml, no charset is specified as the file is treated as us-ascii. For different charset, it needs to specified in the header. For XML use in PHP, the Content-type is specified as ‘application/xml’ and charset to be ‘utf-8’. Content-type Header is part of the HTTP protocol and tells the client or server what type of data to expect and how to interpret it.

Читайте также:  Html use link rel

Examples of PHP XML header

Different examples are mentioned below:

Example #1

   "; echo ""; echo "Hello, this is first PHP XML header"; echo "\n"; echo "Run the code to see the output"; echo ""; ?> 

PHP XML header 1

Here the content type is header is now in XML format.

XML is supported by a wide range of web users and XML tools which are device neutral, vendor-neutral and platform-neutral.

Content-type: text/xml; charset="utf-8"

Above is the recommended charset value to be used with text/xml. MIME and xml processors consider the entity as UTF-8 enclosed. If in cases where data is sent using SMTP request, xml has to use content transfer encoding or base64 encoding. For other types of requests like ESMTP, NNTP, HTTP, etc., the content transfer encoding is not required.

Content-type: text/xml; charset=»utf-16″

utf-16 charset is used only when the xml is transmitted through HTTP with a binary clean protocol without performing any CR and LF transformations. As HTTP is a binary protocol, the content transfer encoding is not necessary here.

Here charset parameter has been omitted. In such cases, xml processors hence assume the charset to be ‘us-ascii’. This default holds true for text/xml is transported using an HTTP request.

But, omission of charset is not at all recommended for text/xml header.

Content-type: application/xml; charset=»utf-16″

It is recommended to be used with header content type as application/xml. As the charset is provided here, xml processors treat the entity as utf-16 encoded.

Content-type: application/xml

Here, there is neither the BOM parameter nor the charset parameter. XML, which is unaware of the processor, should not make any assumptions about the XML entity’s charset.

Example #2

    "Karthik", "empid" => 675, "role" => "UI developer", "age" => 25, "city" => "Vizag" ]; echo json_encode($arr); ?> 

empName

Example #3

   "; $data = [1,2,3,4,5,6,7,8,9]; echo json_encode($data); ?> 

PHP XML header 3

Conclusion

With this, we conclude our topic ‘PHP XML header’. We have seen what PHP XML header is; changing the content type to XML brings out a lot of difference for the http request-response. We have analyzed the syntax for declaring the xml header in PHP code. A charset is one of the important parts of PHP which describes the form of data sent. I saw various charsets such as utf-8 and utf-16, default us-ascii charsets. Also saw how the php xml header works with some of the examples listed above.

Читайте также:  View button in html

This is a guide to the PHP XML header. Here we discuss the introduction to PHP XML header along with examples for better understanding. You may also have a look at the following articles to learn more –

25+ Hours of HD Videos
5 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

92+ Hours of HD Videos
22 Courses
2 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

83+ Hours of HD Videos
16 Courses
1 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

PHP Course Bundle — 8 Courses in 1 | 3 Mock Tests
43+ Hours of HD Videos
8 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Работа с MIME-типами в PHP

«Internet Media Types» или «Медиа типы» — является стандартом RFC 6838, который описывает формат файла. Причем браузеры используют MIME-типы в качестве основного критерия, не воспринимая расширения файлов.

MIME-тип состоит из типа и подтипа — двух значений разделённых « / », без использования пробелов и в нижнем регистре, например HTML страница:

Полный список MIME типов можно посмотреть тут.

К медиа типу может быть добавлен параметр для указания дополнительных деталей (например кодировка):

Как узнать MIME-тип загруженного файла

При загрузке файла через форму, MIME-тип файла доступен в массиве $_FILES , например:

Для определения MIME уже загруженного файла существует PHP-функция mime_content_type().

echo mime_content_type(__DIR__ . '/image.png'); // image/png echo mime_content_type(__DIR__ . '/text.txt'); // text/plain

При работе с изображениями, MIME-тип можно получить с помощью функции getimagesize():

$filename = __DIR__ . '/image.png'; $info = getimagesize($filename); print_r($info);

Результат:

Array ( [0] => 221 [1] => 96 [2] => 3 [3] => width="221" height="96" [bits] => 8 [mime] => image/png )

Важно помнить что при проверке файлов нельзя полагаться только на проверку MIME, т.к. его значение может быть скомпрометировано. Поэтому нужно проводить более детальную проверку (например по размеру изображения или его пересохранить в предполагаемом формате).

Отправка файлов из PHP

В PHP-скриптах, перед отправкой файлов клиенту, необходимо отправлять заголовок Content-Type , например файл XML:

$content = '. '; header("Content-Type: text/xml; charset=utf-8"); echo $content; exit();
$file = ROOT_DIR . '/market.zip'; header('Content-type: application/zip'); header('Content-Transfer-Encoding: Binary'); header('Content-length: ' . filesize($file)); header('Content-disposition: attachment; filename="' . basename($file) . '"'); readfile($file); exit();

Вывод изображения в зависимости от расширения файла:

$filename = __DIR__ . '/image.png'; $ext = mb_strtolower(mb_substr(mb_strrchr($filename, '.'), 1)); switch ($ext) < case 'png': header('Content-type: image/png'); break; case 'jpg': case 'jpeg': header('Content-type: image/jpeg'); break; case 'gif': header('Content-type: image/gif'); break; case 'wepb': header('Content-type: image/webp'); break; >readfile($filename); exit();

Источник

Оцените статью