Serializing XML With PHP
|
|
Serializing XML With PHP |
Build nested XML documents from PHP data structures with XML_Serializer |
| Anatomy Class | Let's take a closer look at how I accomplished this. 1. The first step is, obviously, to include the XML_Serializer class file: // include class file include("Serializer.php"); ?> You can either provide an absolute path to this file, or do what most lazy programmers do - include the path to your PEAR installation in PHP's "include_path" variable, so that you can access any of the PEAR classes without needing to type in long, convoluted file paths. 2. Next, an object of the class needs to be initialized, and assigned to a PHP variable. // create object $serializer = new XML_Serializer(); ?> This variable serves as the control point for future manipulation of XML_Serializer properties and methods. 3. Next, you need to put together the data that you plan to encode in XML. The simplest way to do this is to create a nested set of arrays whose structure mimics that of the final XML document you desire. // create array to be serialized $xml = array ( "book" => array ( "title" => "Oliver Twist", "author" => "Charles Dickens")); ?> 4. With all the pieces in place, all that's left is to perform the transformation. This is done via the object's serialize() method, which accepts a PHP structure and returns a result code indicating whether or not the serialization was successful. // perform serialization $result = $serializer->serialize($xml); ?> 5. Once the serialization is complete, you can do something useful with it - write it to a file, pass it through a SAX parser or - as I've done here - simply output it to the screen for all to admire: // check result code and display XML if success if($result === true) { echo $serializer->getSerializedData(); } ?> The getSerializedData() method returns the serialized XML document tree as is, and serves a very useful purpose in debugging - you'll see it often over the next few pages. |
Serializing XML With PHP |
Build nested XML documents from PHP data structures with XML_Serializer |
| Total Satisfaction | Now, if you're a nitpicker, the output of the example on the previous page still won't satisfy you. Here's why: 1. The serialized XML document does not contain the XML declaration at the top. 2. The root element of the document is called , whereas what you actually want is for it to be . 3. The XML document is not correctly indented. In order to account for these requirements, XML_Serializer comes with a setOption() method, which allows you to customize the behaviour of the serializer to your needs. To illustrate, consider the following example, which solves the first problem noted above: // include class file include("Serializer.php"); // create object $serializer = new XML_Serializer(); // create array to be serialized $xml = array ( "book" => array ( "title" => "Oliver Twist", "author" => "Charles Dickens")); // add XML declaration $serializer->setOption("addDecl", true); // perform serialization $result = $serializer->serialize($xml); // check result code and display XML if success if($result === true) { echo $serializer->getSerializedData(); } ?> Here's the output: Charles Dickens Thus, the setOption() method takes two arguments - a variable and its value - and uses that information to tell the serializer how to return the XML document. Next, how about fixing the root element and the indentation? // include class file include("Serializer.php"); // create object $serializer = new XML_Serializer(); // create array to be serialized $xml = array ( "book" => array ( "title" => "Oliver Twist", "author" => "Charles Dickens")); // add XML declaration $serializer->setOption("addDecl", true); // indent elements $serializer->setOption("indent", " "); // set name for root element $serializer->setOption("rootName", "library"); // perform serialization $result = $serializer->serialize($xml); // check result code and display XML if success if($result === true) { echo $serializer->getSerializedData(); } ?> And here's the result: Charles Dickens Pretty, isn't it? |
Serializing XML With PHP |
Build nested XML documents from PHP data structures with XML_Serializer |
| No Attribution | Now, what about those pesky attributes? Well, XML_Serializer comes with an option that allows you to represent array keys as attributes of the enclosing element (instead of elements themselves). Take a look: // include class file include("Serializer.php"); // create object $serializer = new XML_Serializer(); // create array to be serialized $xml = array ( "book" => array ( "title" => "Oliver Twist", "author" => "Charles Dickens")); // add XML declaration $serializer->setOption("addDecl", true); // indent elements $serializer->setOption("indent", " "); // set name for root element $serializer->setOption("rootName", "library"); // represent scalar values as attributes instead of element $serializer->setOption("scalarAsAttributes", true); // perform serialization $result = $serializer->serialize($xml); // check result code and display XML if success if($result === true) { echo $serializer->getSerializedData(); } ?> Here's the output: Note that in order for this to work, the array key which is to be represented as an attribute should point to a single scalar value and not another array or object. To understand this better, consider the following example, which demonstrates the difference: // include class file include("Serializer.php"); // create object $serializer = new XML_Serializer(); // create array to be serialized $xml = array ( "book" => array ( "title" => "Oliver Twist", "author" => "Charles Dickens", "price" => array ( "currency" => "USD", "amount" => 24.50))); // add XML declaration $serializer->setOption("addDecl", true); // indent elements $serializer->setOption("indent", " "); // set name for root element $serializer->setOption("rootName", "library"); // represent scalar values as attributes instead of element $serializer->setOption("scalarAsAttributes", true); // perform serialization $result = $serializer->serialize($xml); // check result code and display XML if success if($result === true) { echo $serializer->getSerializedData(); } ?> And here's the revised output: To add attributes to the root node, set them with the "rootAttributes" option, as below: // include class file include("Serializer.php"); // create object $serializer = new XML_Serializer(); // create array $xml = array("name" => "John Doe", "age" => 34, "sex" => "male"); // add XML declaration $serializer->setOption("addDecl", true); // indent elements $serializer->setOption("indent", " "); // set name for root element $serializer->setOption("rootName", "person"); // set attributes for root element $serializer->setOption("rootAttributes", array("id" => 346747)); // perform serialization $result = $serializer->serialize($xml); // check result code and display XML if success if($result === true) { echo $serializer->getSerializedData(); } ?> Here's the output: John Doe 34 male |
Serializing XML With PHP |
Build nested XML documents from PHP data structures with XML_Serializer |
| An Object Lesson | You can also serialize objects, in much the same way as you serialize arrays. Take a look at the following example, which demonstrates how: // object definition class Automobile { // object properties var $color; var $year; var $model; function setAttributes($c, $y, $m) { $this->color = $c; $this->year = $y; $this->model = $m; } } // include class file include("Serializer.php"); // create object $serializer = new XML_Serializer(); // create object to be serialized $car = new Automobile; $car->setAttributes("blue", 1982, "Mustang"); // add XML declaration $serializer->setOption("addDecl", true); // indent elements $serializer->setOption("indent", " "); // set name for root element $serializer->setOption("rootName", "car"); // perform serialization $result = $serializer->serialize($car); // check result code and display XML if success if($result === true) { echo $serializer->getSerializedData(); } ?> In this example, I've first defined a class called Automobile, and created some methods and properties for it. Then, further down in the script, I've instantiated an object of the class and set some very specific values for the object's properties. This object has then been serialized via XML_Serializer's serialize() method. Here's the result: blue 1982 Mustang |
Serializing XML With PHP |
Build nested XML documents from PHP data structures with XML_Serializer |
| Not My Type | One of XML_Serializer's other interesting features is its ability to store data type information along with each value in the XML document. Called "type hints", this data type information can help in distinguishing between the integer 6 and the string "6", and comes in handy if your XML application is strongly typed. To enable type hints, you need to simply set the "typeHints" option to true. The following example illustrates: // include class file include("Serializer.php"); // set options $options = array( "addDecl" => true, "indent" => " ", "rootName" => "car", "typeHints" => true); // create object $serializer = new XML_Serializer($options); // create array $car = array("color" => "blue", "year" => 1982, "model" => "Mustang", "price" => 15000.00); // perform serialization $result = $serializer->serialize($car); // check result code and display XML if success if($result === true) { echo $serializer->getSerializedData(); } ?> Once type hints are enabled, every element within the XML document will bear an additional attribute indicating the data type of the value contained within it. Here's what the output of the example above looks like: blue 1982 Mustang 15000 Note that in the example above, I've used a slightly different method to set serializer options - I've created an array of options and values, and passed the array to the object constructor. When you have a large number of options to set, this method can save you a few lines of code. |
Serializing XML With PHP |
Build nested XML documents from PHP data structures with XML_Serializer |
| Travelling In Reverse | Good things come in twos - Mickey and Donald, Tom and Jerry, yin and yang - and so it's no surprise that XML_Serializer has a doppelganger of its own. Called XML_Unserializer, this class can take an XML document and convert it into a series of nested PHP structures, suitable for use in a PHP script. In order to understand how this works, consider the following XML document: Arthur Conan Doyle 24.95 Yann Martel 7.99 Lonely Planet 16.99 Now, in order to convert this XML document into a PHP structure, simply put XML_Unserializer to work on it, as below: // include class file include("Unserializer.php"); // create object $unserializer = &new XML_Unserializer(); // unserialize the document $result = $unserializer->unserialize("library.xml", true); // dump the result $data = $unserializer->getUnserializedData(); print_r($data); ?> Here, the unserialize() method accepts either a string containing XML data or an XML file (set the second argument to false or true depending on which one you are passing) and returns a PHP structure representing the XML document. Here's what the output looks like: Array ( [book] => Array ( [0] => Array ( [title] => The Adventures of Sherlock Holmes [author] => Arthur Conan Doyle [price] => 24.95 ) [1] => Array ( [title] => Life of Pi [author] => Yann Martel [price] => 7.99 ) [2] => Array ( [title] => Europe on a Shoestring [author] => Lonely Planet [price] => 16.99 ) ) ) Now, in order to access the title of the third book (for example), you would use the notation $data['book'][2]['title']; which would return Europe on a Shoestring Note that XML_Unserializer uses the type hints generated in the serialization process to accurately map XML elements to PHP data types. If these hints are unavailable (as in the example above), XML_Unserializer will "guess" the type of each value. A look at the source code of the class reveals that "complex structures will be arrays and tags with only CData in them will be strings." |
|
Serializing XML With PHP |
Build nested XML documents from PHP data structures with XML_Serializer |
| Employment Options | Now, while all this is fine and dandy, how about using all this new-found knowledge for something practical? This next example does just that, demonstrating how the XML_Serializer class can be used to convert data stored in a MySQL database into an XML document, and write it to a file for later use. Here's the MySQL table I'll be using, mysql> SELECT * FROM employees; +-----+--------+--------+-----+-----+----------------+---------+ | id | lname | fname | age | sex | department | country | +-----+--------+--------+-----+-----+----------------+---------+ | 54 | Doe | John | 27 | M | Engineering | US | | 127 | Jones | Sue | 31 | F | Finance | UK | | 113 | Woo | David | 26 | M | Administration | CN | | 175 | Thomas | James | 34 | M | Finance | US | | 168 | Kent | Jane | 29 | F | Administration | US | | 12 | Kamath | Ravina | 35 | F | Finance | IN | +-----+--------+--------+-----+-----+----------------+---------+ 6 rows in set (0.11 sec) and here's what I want my target XML document to look like: Doe John 27 M Engineering US Jones Sue 31 F Finance UK Woo David 26 M Administration CN Thomas James 34 M Finance US Kent Jane 29 F Administration US Kamath Ravina 35 F Finance IN With XML_Serializer, accomplishing this is a matter of a few lines of code. Here they are: // include class file include("Serializer.php"); // set output filename $filename = 'employees.xml'; // set options $options = array( "addDecl" => true, "defaultTagName" => "employee", "indent" => " ", "rootName" => "employees"); // create object $serializer = new XML_Serializer($options); // open connection to database $connection = mysql_connect("localhost", "user", "secret") or die ("Unable to connect!"); // select database mysql_select_db("db1") or die ("Unable to select database!"); // execute query $query = "SELECT * FROM employees"; $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()); // iterate through rows and print column data while ($row = mysql_fetch_array($result)) { $xml[] = array ( "lname" => $row[1], "fname" => $row[2], "age" => $row[3], "sex" => $row[4], "department" => $row[5], "country" => $row[6]); } // close database connection mysql_close($connection); // perform serialization $result = $serializer->serialize($xml); // open file if (!$handle = fopen($filename, 'w')) { print "Cannot open file ($filename)"; exit; } // write XML to file if (!fwrite($handle, $serializer->getSerializedData())) { print "Cannot write to file ($filename)"; exit; } // close file fclose($handle); ?> Pretty simple, once you know how it works. First, I've opened up a connection to the database and retrieved all the records from the table. Then I've instantiated a new document tree and iterated over the result set, adding a new set of nodes to the tree at each iteration. Finally, once all the rows have been processed, the dynamically generated tree is written to a file for later use. |
Serializing XML With PHP |
Build nested XML documents from PHP data structures with XML_Serializer |
| Linking Out | And that's about it for this article. Over the last few pages, I showed you how you to build an XML document tree even if your PHP build doesn't support the XML DOM, via the free add-on XML_Serializer class from PEAR. I showed you how to programmatically create an XML document from an array or an object, how to indent XML document nodes, how to attach attributes to elements, and how to customize the behaviour of the serializer. I also showed you to how to reverse-serialize XML documents into PHP arrays or objects for use within a PHP script, together with examples of how type hints could help to make this a more accurate process. Finally, I wrapped things up with a composite example that demonstrated a practical, real-world use for all this code - converting the data in a MySQL database into XML and writing it to a file. All this is, of course, only the tip of the iceberg - there are an infinite number of possibilities with power like this at your disposal. To find out what else you can do with XML and PHP, I'd encourage you to visit the following links: XML Basics, at http://www.melonfire.com/community/columns/trog/article.php?id=78 XSL Basics, at http://www.melonfire.com/community/columns/trog/article.php?id=82 Using PHP With XML, at http://www.melonfire.com/community/columns/trog/article.php?id=71 XSLT Transformation With PHP And Sablotron, at http://www.melonfire.com/community/columns/trog/article.php?id=97 Building XML Trees With PHP, at http://www.melonfire.com/community/columns/trog/article.php?id=180 The XML and PHP book, at http://www.xmlphp.com/ Till next time...be good! |

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

세션 납치는 다음 단계를 통해 달성 할 수 있습니다. 1. 세션 ID를 얻으십시오. 2. 세션 ID 사용, 3. 세션을 활성 상태로 유지하십시오. PHP에서 세션 납치를 방지하는 방법에는 다음이 포함됩니다. 1. 세션 _regenerate_id () 함수를 사용하여 세션 ID를 재생산합니다. 2. 데이터베이스를 통해 세션 데이터를 저장하십시오.

PHP에는 4 가지 주요 오류 유형이 있습니다. 1. NOTICE : 가장 작은 것은 정의되지 않은 변수에 액세스하는 것과 같이 프로그램을 방해하지 않습니다. 2. 경고 : 심각한 통지는 파일을 포함하지 않는 것과 같은 프로그램을 종료하지 않습니다. 3. FatalError : 가장 심각한 것은 기능을 부르는 것과 같은 프로그램을 종료합니다. 4. parseerror : 구문 오류는 엔드 태그를 추가하는 것을 잊어 버리는 것과 같이 프로그램이 실행되는 것을 방지합니다.

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

HTTP 요청 방법에는 각각 리소스를 확보, 제출, 업데이트 및 삭제하는 데 사용되는 Get, Post, Put and Delete가 포함됩니다. 1. GET 방법은 리소스를 얻는 데 사용되며 읽기 작업에 적합합니다. 2. 게시물은 데이터를 제출하는 데 사용되며 종종 새로운 리소스를 만드는 데 사용됩니다. 3. PUT 방법은 리소스를 업데이트하는 데 사용되며 완전한 업데이트에 적합합니다. 4. 삭제 방법은 자원을 삭제하는 데 사용되며 삭제 작업에 적합합니다.

PHP에서 Password_hash 및 Password_Verify 기능을 사용하여 보안 비밀번호 해싱을 구현해야하며 MD5 또는 SHA1을 사용해서는 안됩니다. 1) Password_hash는 보안을 향상시키기 위해 소금 값이 포함 된 해시를 생성합니다. 2) Password_verify 암호를 확인하고 해시 값을 비교하여 보안을 보장합니다. 3) MD5 및 SHA1은 취약하고 소금 값이 부족하며 현대 암호 보안에는 적합하지 않습니다.

화살표 기능은 PHP7.4에 도입되었으며 단순화 된 형태의 짧은 폐쇄입니다. 1) => 연산자를 사용하여 정의되어 기능을 생략하고 키워드를 사용합니다. 2) 화살표 기능은 사용 키워드없이 현재 스코프 변수를 자동으로 캡처합니다. 3) 종종 코드 단순성과 가독성을 향상시키기 위해 콜백 기능 및 짧은 계산에 사용됩니다.

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.
