PHP generates XML format data and parse XML data program

Source: Internet
Author: User
Tags foreach php file php code

Look at the XML document first

The code is as follows Copy Code

<?xml version= "1.0" encoding= "Utf-8"?>
<article>
<item>
<title size= "1" >title1</title>
<content>content1</content>
<pubdate>2009-10-11</pubdate>
</item>
<item>
<title size= "1" >title2</title>
<content>content2</content>
<pubdate>2009-11-11</pubdate>
</item>
</article>

So how do we use PHP to generate XML format data?

Method 1: Generate the string using pure PHP code and write this string to a file with XML suffix. This is the most original way to generate XML, but it works!
The PHP code is as follows:

The code is as follows Copy Code
? Php
$data _array = Array (
Array
' title ' => ' Title1 ',
' Content ' => ' content1 ',
' pubdate ' => ' 2009-10-11 ',
),
Array
' title ' => ' Title2 ',
' Content ' => ' Content2 ',
' pubdate ' => ' 2009-11-11 ',
)
);
$title _size = 1;

$xml = "<?xml version=" 1.0 "encoding=" Utf-8 ">n";
$xml. = "<article>n";

foreach ($data _array as $data) {
$xml. = Create_item ($data [' title '], $title _size, $data [' content '], $data [' pubdate ']);
}

$xml. = "</article>n";

Echo $xml;

To create an XML item
function Create_item ($title _data, $title _size, $content _data, $pubdate _data) {
$item = "<item>n";
$item. = "<title size=" ". $title _size. ">". $title _data. "</title>n";
$item. = "<content>". $content _data. "</content>n";
$item. = "<pubdate>". $pubdate _data. "</pubdate>n";
$item. = "</item>n";

return $item;
}


?>

"DOMDocument"
Method 2: Generate an XML file using DOMDocument
Create nodes using the CreateElement method,
Create text content using the createTextNode method,
Add child nodes using the AppendChild method,
Creating properties using the CreateAttribute method

The code is as follows Copy Code

? Php
$data _array = Array (
Array
' title ' => ' Title1 ',
' Content ' => ' content1 ',
' pubdate ' => ' 2009-10-11 ',
),
Array
' title ' => ' Title2 ',
' Content ' => ' Content2 ',
' pubdate ' => ' 2009-11-11 ',
)
);

Property array
$attribute _array = Array (
' title ' => Array (
' Size ' => 1
)
);

Create an XML document and set up an XML version and encoding ...
$dom =new DOMDocument (' 1.0 ', ' utf-8 ');

To create a root node
$article = $dom->createelement (' article ');
$dom->appendchild ($article);

foreach ($data _array as $data) {
$item = $dom->createelement (' item ');
$article->appendchild ($item);

Create_item ($dom, $item, $data, $attribute _array);
}

echo $dom->savexml ();

function Create_item ($dom, $item, $data, $attribute) {
if (Is_array ($data)) {
foreach ($data as $key => $val) {
Creating elements
$ $key = $dom->createelement ($key);
$item->appendchild ($ $key);

Create an element value
$text = $dom->createtextnode ($val);
$ $key->appendchild ($text);

if (Isset ($attribute [$key])) {//If there is a related property to be set for this field
foreach ($attribute [$key] as $akey => $row) {
To create an attribute node
$ $akey = $dom->createattribute ($akey);
$ $key->appendchild ($ $akey);

Creating a property value node
$aval = $dom->createtextnode ($row);
$ $akey->appendchild ($aval);
}
}//End If
}
}//End If
}//End Function
?>

Below we take the Student information form student, needs to provide to the third party to call, and has id,name,sex,age separately records student's name, gender, age and so on information.

The code is as follows Copy Code

CREATE TABLE ' Student ' (

' id ' int (one) not NULL auto_increment,

' Name ' varchar not NULL,

' Sex ' varchar not NULL,

' Age ' smallint (3) is not NULL default ' 0′,

PRIMARY KEY (' id ')

) Engine=myisam DEFAULT Charset=utf8;

First, establish the createxml.php file, connect the database first, obtain the data.

The code is as follows Copy Code


Include_once ("connect.php"); Connecting to a 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 ']

);

}

This time, the data is stored in the $arr, you can use Print_r print the data test.


Next, create XML, loop arrays, and write data to the corresponding nodes in the XML.

  code is as follows copy code

 

$doc = new DOMDocument (' 1.0′, ' utf-8′); Declaring versions and Encodings

$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 PHP's built-in class DOMDocument to process and generate XML. The resulting XML format

The code is as follows Copy Code


<?xml version= "1.0″encoding=" utf-8″?>

<root>

<data>

<name> Li Wanghao </name>

<sex> male </sex>

<age>21</age>

</data>

...

</root>

Get XML Format data

Now we're going to assume that to get student information from a third party, the data format is XML, we need to parse the XML using PHP, and then display the parsed data or write it to the local database. And the key step here is parsing XML.

PHP has a number of ways to parse XML, where PHP provides a built-in XmlReader class for sequentially browsing through XML files, and you can imagine a cursor walking through the entire file node and grabbing the desired content. Using XmlReader is efficient, especially when reading very large XML data, and compared to other methods, using XmlReader consumes very little memory.

  code is as follows copy code
"

Header ("content-type:text/html; Charset=utf-8″);

$url = "Your XML path";

$reader = new XMLReader ();//Instantiate XMLReader

$reader->open ($url);//Get XML

$i =1;

while ($reader->read ()) {

if ($reader->nodetype = = Xmlreader::text) {//Judge node type

$m = $i%3;

if ($m ==1)

$name = $reader->value;//Read node value

If ($m ==2)

$sex = $reader->value;

If ($m ==0) {

$age = $reader->value;

$arr [] = array (

' name ' => $name,

' sex ' => $sex,

' age ' => $age

);

}

$i + +;

}

}

//print_r ($arr);

In order to separate the data name,sex from the age, we use $i%3 to determine the modulo, because the information under node data is present in the acquired XML as 3 subnodes.

There are a lot of ways to generate and read XML documents, so I'm not going to introduce them, so you can refer to the documentation below.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.