intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Professional PHP Programming phần 5

Chia sẻ: Hà Nguyễn Thúy Quỳnh | Ngày: | Loại File: PDF | Số trang:86

51
lượt xem
5
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

ví dụ thường được sử dụng trong các kịch bản của bạn. Như đã nói, khả năng sử dụng các lớp học của bạn trong nhiều kịch bản khác nhau là một trong những lý do quan trọng để tạo ra chúng.Lập trình hướng đối tượng cho phép lập trình để tham khảo các biến liên quan và các chức năng như một thực thể duy nhất được gọi là một đối tượng hoặc dụ. Kết hợp ba

Chủ đề:
Lưu

Nội dung Text: Professional PHP Programming phần 5

  1. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com H owever, as we noted above, there is also an alternative syntax, whereby we place the closing slash at the end of the opening element: T he following line defines an empty element i mage , with an attribute s rc w ith the value l ogo.gif : Processing Instructions X ML processing instructions contain information for the application using the XML document. Processing instructions do not constitute the part of the character data of the document – the XML parser should pass these instructions unchanged to the application. The syntax of the processing instruction might be strangely familiar to you: I n the following example, p hp i s the target application and p rint "This XML document was created on Jan-07, 1999"; i s the instruction: Entity References E ntities are used in the document as a way of avoiding typing long pieces of text many times in a document. Entities are declared in the document's DTD (we will see later how to declare entities, when we look at DTDs in more detail). The declared entities can be referenced throughout the document. When the document is parsed by an XML parser, it replaces the entity reference with the text defined in the entity declaration. There are two types of entities – internal and external. The replacement text for an internal entity is specified in an entity declaration, whereas the replacement text for an external entity resides in a separate file, the location of which is specified in the entity declaration. After the entity has been declared, it can be referenced within the document using the following syntax: &nameofentity; N ote that there should be no space between the ampersand ( & ), the entity name and the semicolon. For example, let's assume that an entity m yname w ith the value " Harish Rawat" h as been declared in the DTD of the document. The entity m yname c an be referred to in the document as: TEAM FLY PRESENTS
  2. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com &myname; T he parser, while parsing the document will replace & myname ; b y H arish Rawat . So the application using the XML document will see the content of the element author as H arish Rawat . Comments C omments can be added in XML documents; the syntax is identical to that for HTML comments: The Document Type Definition T he document type definition of an XML document is defined within a declaration known as the d ocument type declaration . The DTD can be contained within this declaration, or the declaration can point to an external document containing the DTD. The DTD consists of element type declarations, attribute list declarations, entity declarations, and notation declarations. We will cover all of these in this section. B e sure to distinguish between the document type d efinition , or DTD, and the d ocument type d eclaration . T he syntax for a document type definition is: T he r ootelementname i s the name of the root element of the document. The declarations for the various elements, attributes, etc., are placed within the square braces. An XML document can also have an external DTD, which can be referenced with the following syntax: T he r ootelementname i s the name of the root element of the document. The location of the file containing the DTD is h ttp://www.harawat.com/books.dtd . Element Type Declarations T he element type declaration indicates whether the element contains other elements, text, or is empty. It also specifies whether the elements are mandatory or optional, and how many times the elements can appear. An element type declaration, specifying that an element can contain character data, looks as follows: TEAM FLY PRESENTS
  3. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com H ere E LEMENT i s a keyword, e lementname i s the name of the element, and # PCDATA i s also a keyword. # PCDATA s tands for "parsed character data", that is, the data that can be handled by the XML parser. For example, the following element declaration specifies that the element t itle c ontains character data: T he syntax of an element type declaration for an empty element is: H ere e lementname i s the name of the element, and E MPTY i s a keyword. For example, the following element type declaration specifies that element i mage i s empty: T he syntax of an element type declaration for an element can contain anything – other elements or parsed character data – is as follows: H ere e lementname i s the name of the element and A NY i s a keyword. An element type declaration for an element that contains only other elements looks like this: H ere the element p arentelement c ontains the child elements c hildelement1 , c hildelement2 , etc. For example, the following element type declaration specifies that the element b ook c ontains the elements t itle , a uthors , i sbn , p rice : T he syntax of element type declaration, specifying that p arentelemnt c ontains either c hildelement1 o r c hildelement2 , … . F or example, the following element type declaration specifies that element u rl c an contain either h ttpurl o r f tpurl : TEAM FLY PRESENTS
  4. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com T he following operators can be used in the element type declaration, to specify the number of allowed instances of elements within the parent element: O perator Description Z ero or more instances of the element is allowed. * O ne or more instance of the element is allowed. + O ptional. ? T he following element type declaration specifies that the element a uthors c ontains zero or more instances of the element a uthor : T he following element type declaration specifies that element a uthors c ontains one or more instances of element a uthor : T he following element type declaration specifies that the element t oc c ontains the element c hapters a nd optionally can contain element a ppendixes : Attribute List Declarations W e saw earlier that an element can have attributes associated with it. The attribute list declaration specifies the attributes which specific elements can take. It also indicates whether the attributes are mandatory or not, the possible values for the attributes, default values etc. The syntax of the attribute list declaration is: H ere e lementname i s the name of the element, a ttrname1 i s the name of an attribute, d atatype1 s pecifies the type of information to be passed with the attribute and f lag1 i ndicates how the default values for the attribute are to be handled. The possible values for the d atatype f ield depend on the type of the attribute. Possible values for the f lags f ield are: TEAM FLY PRESENTS
  5. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com F lag Description T his flag indicates that the attribute should be present in all instances of the # REQUIRED element. If the attribute is not present in an instance of the element, then the document is not a valid document. T his flag indicates that the application can assume a default value for the # IMPLIED attribute if the attribute is not specified in an element. T his flag indicates that the attribute can have only one value for all # FIXED instances of elements in the document. CDATA Attributes C DATA a ttributes can have any character data as their value. The following attribute list declaration specifies that instances of the element p rice m ust have an attribute c urrency w hose value can be any character data: Enumerated Attributes E numerated attributes can take one of the list of values provided in the declaration. The following attribute list declaration specifies that instances of the element a uthor c an have an attribute g ender , with a value of either " male" o r " female" : ID and IDREF Attributes A ttributes of type I D m ust have a unique value in an XML document. These attributes are used to uniquely identify instances of elements in the document. The following attribute list declaration specifies that instances of element e mployee , must have an attribute e mployeeid , and the value of it should be unique in the XML document: T he value of attributes of type I DREF m ust match the value of an I D a ttribute on some element in the XML document. Similarly, the values of attributes of type I DREFS m ust contain whitespace- delimited I D v alues in the document. Attributes of type I DREF a nd I DREFS a re used to establish links between elements in the document. The following attribute list declaration is used to establish a link between an employee and his or her manager and subordinates.
  6. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com subordinatesid IDREFS #IMPLIED> Entity Attributes E ntity attributes provide a mechanism for referring to non-XML (binary) data from an XML document. The value of an entity attribute must match the name of an external entity declaration referring to non-XML data. The following attribute list declaration specifies that the element b ook , can have an entity attribute l ogo . Notation Declarations S ometimes elements in XML documents might refer to an external file containing data in a format that an XML parser cannot read. Suppose we have an XML document containing the details of book. We may want to put a reference to a GIF image of the cover along with the details of the book. The XML parser would not be able to process this data, so we need a mechanism to identify a helper application which will process this non-XML data. Notation declarations allow the XML parser to identify helper applications, which can be used to process non-XML data. A notation declaration provides a name and an external identifier for a type of non-XML (unparsed) data. The external identifier for the notation allows the XML application to locate a helper application capable of processing data in the given notation. For example, the following notation declaration specifies " file:///usr/bin/netscape" a s the helper application for non-XML data of type " gif" : Entity Declarations E ntity declarations define entities which are used within the XML document. Whenever the XML parser encounters an entity reference in the XML document, it replaces it with the contents of the entity as defined in the entity declaration. Internal entity declarations are in the following format: T his entity declaration defines an entity m yname , with the value " Harish Rawat" . The following is an example of an external entity declaration, referring to a file containing XML data: T his entity declaration defines an entity named d escription1 , with " description1.xml" a s the system identifier. A "system identifier" is the location of the file containing the data. TEAM FLY PRESENTS
  7. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com W hen declaring external entity declarations, public identifiers for the entity can also be specified. The XML parser, on encountering the external entity reference first tries to resolve the reference using the public identifier and only when it fails it tries to use system identifier. In this example, the entity d escription1 i s declared with the public identifier " http://www.harawat.com/description1.xml" , and the system identifier " description1.xml" :
  8. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The PHP XML API A P HP script which parses an XML document must perform the following operations: 1 . C reate an XML parser. 2 . R egister handler functions (callback functions) with the parser. The parser will call these registered handlers as and when it recognizes different nodes in the XML document. Most of the application logic is implemented in these handler functions. 3 . R ead the data from the XML file, and pass the data to the parser. This is where the actual parsing of the data occur. 4. F ree the parser, after the complete file has been parsed. We will have a quick look at what this means in practice by showing a very simple XML parser (in fact, just about the simplest possible!), before going on to look at the individual functions in turn.
  9. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com } // Read chunks of 4K from the file, and pass it to the parser while ($data = fread($fp, 4096)) { if (!xml_parse($parser, $data, feof($fp))) { die(sprintf("XML error %d %d", xml_get_current_line_number($parser), xml_get_current_column_number($parser))); } } ?> I f we run this script against the following XML file: Pro PHP XML in IE5 Pro XML T his will produce this output in the browser: TEAM FLY PRESENTS
  10. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com N ow we'll go on to discuss the functions in detail. In the following sections, all the XML-related functions will be described, along with examples of their use. Creating an XML Parser T he function x ml_parser_create() c reates an XML parser context. int xml_parser_create(string [encoding_parameter]); P aramter Optional Description Default Y es The character source encoding e ncoding_parameter " ISO-8859-1" that will be used by the parser. The source encoding once set cannot be changed later. The possible values are TEAM FLY PRESENTS
  11. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com " ISO-8859-1" , " US- ASCII" a nd " UTF-8" . T he function returns a handle (a positive integer value) on success, and f alse o n error. The handle returned by x ml_parser_create() w ill be passed as an argument to all the function calls which register handler functions with the parser, or change the options of the parser. We will see these function calls shortly. We can define multiple parsers in a single PHP script. You may want to do it if you are parsing more than one XML document in the script. Registering Handler functions B efore we can parse an XML document, we need to write functions which will handle the various nodes of the XML document. For example, we need to write a function which will handle the opening tag of XML elements, and another which will handle the closing tags. We also need to assign handlers for character data, processing instructions, etc. These handlers must be registered with the XML parser before the document can be parsed. Registering Element Handlers T he function x ml_set_element_handler() r egisters "start" and "end" element handler functions with the XML parser. Its syntax is: int xml_set_element_handler(int parser, string startElementHandler, string endElementHandler); P arameter Optional Description No The handler of an XML p arser parser, with which the start and end element handlers are registered No The name of the start s tartElementHandler element handler function. If null is specified then no start element handler is registered. No The name of the end e ndElenmentHandler element handler function. If null is specified then no end element handler is registered. T he function returns t rue o n success, or f alse i f the call fails. The function call will return f alse i f p arser i s not a valid parser handle. TEAM FLY PRESENTS
  12. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com T he registered handler functions s tartElementHandler a nd e ndElementHandler s hould exist when an XML document is parsed; if they do not, a warning will be generated. Start Element Handler T he user-defined start element handler function, registered with the parser through an x ml_set_element_handler() f unction call, will be called when the parser encounters the opening tag of an element in the document. The function must be defined with the following syntax: startElementHandler(int parser, string name, string attribs[]); P arameter Optional? Description No Reference to the XML p arser parser which is calling this function No The name of the n ame element No An associative array a ttribs[] containing the attributes of the element. F or example, suppose we are parsing the following line of an XML document: Harish Rawat T he XML parser will call our registered start element handler function with the following parameters: startElementHandler($parser, "author", array("gender"=>"male", "age"=>"24"); End Element Handler T he user-defined end element handler function, registered with the parser through x ml_set_element_handler() f unction call, will be called when the parser encounters a end tag of an element in the document. This function should have the following syntax: endElementHandler(int parser, string name); P arameter Optional Description No Reference to the XML p arser parser which is calling this function No Tag name of the n ame element TEAM FLY PRESENTS
  13. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com F or example, if we parse the following line of an XML document: Harish Rawat T he registered end element handler function will be called with the following parameters: endElementHandler($parser, "author"); N otice that the value of the n ame p arameter is " author" a nd not " /author" . The Character Data Handler T he function x ml_set_character_data_handler() r egisters the character data handler with the XML parser. The character data handler is called by the parser, for all non-markup contents of the XML document: int xml_set_character_data_handler (int parser, string characterDataHandler); P arameter Optional Description No The handle for an p arser XML parser, with which the character data handler is registered No The name of the c haracterDataHandler character data handler function. If n ull i s specified then no character data handler is registered. T he function returns true on success else false is returned. The function will return false if the p arser i s not a valid parser handle. The registered handler function should exist when parsing of an XML document is done, else a error is generated. Prototype for the Character Data Handler T he user-defined character data handler function, registered with the parser through a call to the x ml_set_character_data_handler() f unction, will be called when the parser encounters non-markup content in the XML document and should have the following syntax: characterDataHandler(int parser, string data); TEAM FLY PRESENTS
  14. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com P arameter Optional Description No Reference to the XML p arser parser which is calling this function. No The character data as d ata present in the XML document. The parser returns the character data as it is, and does not remove any white spaces. W hile parsing the contents of an element, the character data handler can be called any number of times. This should be kept in mind while defining the character data handler function. For example, while parsing the following line of an XML document: Harish Rawat T he character data handler can be called once with the following parameters: characterDataHandler($parser, "Harish Rawat"); O r it can be called twice; firstly as: characterDataHandler($parser, "Harish "); A nd again as: characterDataHandler($parser, "Rawat"); The Processing Instruction Handler T he function x ml_set_processing_instruction_handler() r egisters with the XML parser the function that will be used to handle processing instructions. The processing instruction handler is called by the parser when it encounters a processing instruction in the XML document: int xml_set_processing_instruction_handler(int parser, string processingInstructionHandler); P arameter Optional Description No The handle for an p arser XML parser with which the processing instruction handler TEAM FLY PRESENTS
  15. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com i s registered No The name of the p rocessingInstruc tionHandler processing instruction handler function. If n ull i s specified then no processing instruction handler is registered. T he function returns t rue o n success or f alse o n failure. The function will return f alse i f p arser i s not a valid parser handle. The registered handler function should exist when an XML is parsed, or an error is generated. Processing instructions, as we saw in the section on the XML Language, are application-specific instructions embedded in the XML document. This is similar to the way we embed PHP instructions in an HTML file. Prototype for the Processing Instruction Handler T he user defined processing instruction handler function, registered with the parser through the x ml_set_processing_instruction_handler() f unction, will be called when the parser encounters processing instructions in the XML document and should have the following syntax: processingInstructionHandler(int parser, string target, string data); P arameter Optional Description No Reference to the XML p arser parser which is calling this function No The target of the t arget processing instruction No Data to be passed to the d ata parser F or example, if we are parsing the following processing instruction in an XML document: T he processing instruction handler will be called with the following parameters: processingInstructionHandler($parser, "php", string "print \"This XML document was created on Jan 01, 1999\";"); A s ample processing instruction handler might look like this: TEAM FLY PRESENTS
  16. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com function piHandler($parser, $target, $data) { if (strcmp(strtolower($target), "php") == 0) { eval($data); } } I f you are defining such a processing instruction handler in your application, then you should do some security checks before executing the code. The code embedded through processing instructions can be malicious – for example, it could delete all the files in the server. One security check could be to execute the code in the processing instructions only if the owner of the XML file and the XML parser are the same. The Notation Declaration Handler T he function x ml_set_notation_decl_handler() r egisters the notation declaration handler with the parser. The notation declaration handler is called by the parser whenever it encounters a notation declaration in the XML document. int xml_set_notation_decl_handler(int parser, string notationDeclarationHandler); P arameter Optional Description No The handle for the p arser XML parser with which the notation declaration handler is registered No The name of the n otationDeclarat ionHandler notation declaration handler function. If n ull i s specified then no notation declaration handler is registered. T he function returns t rue o n success, otherwise f alse i s returned. The function will return f alse i f p arser i s not a valid parser handle. An error will be generated when the XML document is parsed if the notation declaration handler does not exist. Prototype for the Notation Declaration Handler T he user defined notation declaration handler function, registered with the parser through a call to the x ml_set_notation_decl_handler() f unction, will be called when the parser encounters notation declarations in the XML document and should have the syntax: notationDeclarationHandler(int parser, string notationName, string base, TEAM FLY PRESENTS
  17. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com string systemId, string publicId); P arameter Optional Description p arser No Reference to the XML parser which is calling this function n otationName No Name of the notation b ase No This is the base for resolving the s ystemId . Currently the value of this parameter will always be a null string. s ystemId No The system identifier of the notation declaration p ublicId No The public identifier of the notation declaration F or example, parsing the following notation declaration of an XML document: W ill cause the notation declaration handler to be called with the following parameters: notationDeclarationHandler($parser, "gif", "", "file:///usr/bin/netscape", ""); L et's implement a sample notation declaration handler. This handler populates the associative array $ helperApps w ith a mapping between the notation name and the name of the application that will handle the unparsed data of type $ notationName . The $ helperApps a rray can be used by the unparsed entity declaration handler to identify the application that should be used to process non- XML data. We will look at the unparsed entity declaration handler shortly. function notationHandler($parser, $notationName, $base, $systemId, $publicId) { global $helperApps; if ($systemId) { $helperApps[$notationName] = $systemId; } else { $helperApps[$notationName] = $publicId; } } TEAM FLY PRESENTS
  18. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The External Entity Reference Handler T he function x ml_set_external_entity_ref_handler() r egisters the external entity reference handler with the XML parser. This function is called by the parser when it encounters an external entity reference in an XML document. Note that the registered handler is called for external entity references and not external entity declarations. Unlike other parsers (such as Microsoft Internet Explorer 5), the XML parser of PHP does not handle external entities. It simply calls the registered external entity reference handler to handle it. int xml_set_external_entity_ref_handler(int parser, string externalEntityRefHandler); P arameter Optional Description p arser No The handle for an XML parser with which the external entity reference handler is registered e xternalEntityRef No The name of the external entity Handler reference handler function. If null is specified then no external entity reference handler is registered. T he function returns t rue o n success; otherwise, f alse i s returned. The function will return f alse i f p arser i s not a valid parser handle. The registered handler function should exist when parsing an XML document, or an error will be generated. Prototype for the External Entity Reference Handler T he user-defined external entity reference handler function, registered with the parser through an x ml_set_external_entity_ref_handler f unction call, will be called when the parser encounters external entity references in the XML document. This should have the following syntax: int externalEntityRefHandler(int parser, string entityName, string base, string systemId, string publicId); P arameter Optional Description TEAM FLY PRESENTS
  19. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com p arser No Reference to the XML parser which is calling this function e ntityName No Name of the entity b ase No This is the base for resolving s ystemId . Currently the value of this parameter will always be a null string. s ystemId No The system identifier of the external entity p ublicId No The public identifier of the external entity T he user-defined external entity reference handler should handle the external references in the XML document. If a t rue v alue is returned by the handler, the parser assumes that the external reference was successfully handled and the parsing continues. If the handler returns f alse , the parser will stop parsing. As an example, suppose that an entity & book_1861002777; i s defined in the DTD of an XML document: A nd the parser comes across the following line in an XML document: &book_1861002777; T he external entity reference handler will be called with the parameters: externalEntityRefHandler($parser, "book_186100277", "", "1861002777.xml", ""); The Unparsed Entity Declaration Handler T he function x ml_set_unparsed_entity_decl_handler r egisters the external entity reference handler with the xml parser. The unparsed entity declaration handler is called by the parser, when it encounters an unparsed entity declaration in an XML document. int xml_set_unparsed_entity_decl_handler(int parser, string unparsedEntityDeclHandler); TEAM FLY PRESENTS
  20. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com P arameter Optional Description p arser No The handle of an XML parser with which the unparsed entity declaration handler is registered u nparsedEntityDeclHa No The name of the unparsed entity ndler declaration handler function. If null is specified then no external entity reference handler is registered. T he function returns t rue o n success or f alse o n failure. The function returns false if p arser i s not a valid parser handle. The registered handler function should exist when an XML is parsed, or an error will be generated. Prototype for the Unparsed Entity Declaration Handler T he user-defined unparsed entity declaration handler function, registered with the parser through an x ml_set_unparsed_entity_decl_handler() f unction call, will be called when the parser encounters an unparsed entity declaration in the XML document. Its syntax is: unparsedEntityDeclHandler(int parser, string entityName, string base, string systemId, string publicId, string notationName); P arameter Optional Description p arser No Reference to the XML parser which is calling this function e ntityName No Name of the entity b ase No This is the base for resolving s ystemId . Currently the value of this parameter will always be a null string. s ystemId No The system identifier of the unparsed entity p ublicId No The public identifier of the unparsed entity n otationName No The name of the notation (defined in TEAM FLY PRESENTS
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2