PHP generates and obtains XML format data. When using data interfaces, we usually need to obtain third-party data interfaces or provide third-party data interfaces. these data formats are generally transmitted in XML or JSON format.
When using data interfaces, we usually need to obtain third-party data interfaces or provide third-party data interfaces. these data formats are usually transmitted in XML or JSON format, this article describes how to use PHP to generate XML format data for third-party calls and how to obtain XML data provided by a third-party.
Generate XML format data
Assume that the system has a student info table student, which must be provided to a third party for calling. the student name, gender, age, and other information are recorded by id, name, sex, and age.
- CREATE TABLE `student` (
- `id` int(11) NOT NULL auto_increment,
- `name` varchar(50) NOT NULL,
- `sex` varchar(10) NOT NULL,
- `age` smallint(3) NOT NULL default '0',
- PRIMARY KEY (`id`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
First, create the createXML. php file, connect to the database, and obtain data.
- Include_once ("connect. php"); // connect to the database
- $ SQL = "select * from student ";
- $ Result = mysql_query ($ SQL) or die ("Invalid query:". mysql_error ());
- While ($ row = mysql_fetch_array ($ result )){
- $ Arr [] = array (
- 'Name' => $ row ['name'],
- 'Sex '=> $ row ['Sex'],
- 'Age' => $ row ['age']
- );
- }
At this time, the data is saved in $ arr. you can use print_r to print the data for testing.
Then, create an xml and circular array to write data to the corresponding xml node.
- $ Doc = new DOMDocument ('1. 0', 'utf-8'); // declare the version and encoding
- $ Doc-> formatOutput = true;
- $ R = $ doc-> createElement ("root ");
- $ Doc-> appendChild ($ r );
- Foreach ($ arr as $ dat ){
- $ B = $ doc-> createElement ("data ");
- $ Name = $ doc-> createElement ("name ");
- $ Name-> appendChild ($ doc-> createTextNode ($ dat ['name']);
- $ B-> appendChild ($ name );
- $ Sex = $ doc-> createElement ("sex ");
- $ Sex-> appendChild ($ doc-> createTextNode ($ dat ['sex']);
- $ B-> appendChild ($ sex );
- $ Age = $ doc-> createElement ("age ");
- $ Age-> appendChild ($ doc-> createTextNode ($ dat ['age']);
- $ B-> appendChild ($ age );
- $ R-> appendChild ($ B );
- }
- Echo $ doc-> saveXML ();
We call the PHP built-in class DOMDocument to process and generate xml. The final generated xml format is as follows:
...