-
-
- title1
- content1
- 2009-10-11
-
-
- title2
- content2
- 2009-11-11
-
Copy code
Method 1, generate directly string
Use pure PHP code to generate a string and write the string to a file with an XML suffix.
-
-
$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 = "n" ;
- $xml .= "n";
foreach ($data_array as $data) {
- $xml .= create_item($data['title'], $title_size , $data['content'], $data['pubdate']);
- }
$xml .= "n";
- echo $xml;< /p>
//Create XML single item
- function create_item($title_data, $title_size, $content_data, $pubdate_data)
- {
- $item = "
- n";
- $item .= "< ;title size="" . $title_size . "">" . $title_data . "n";
- $item .= "" . $content_data . "n ";
- $item .= " " . $pubdate_data . "n";
- $item .= "n";
return $item;
- }
- ?>
-
Copy code
Method 2, use DomDocument to generate XML files
Steps:
1. Create nodes using the createElement method.
2. Create text content using the createTextNode method,
3. Add child nodes using the appendChild method.
4. Create attributes using the createAttribute method
-
-
$data_array = array( - array(
- 'title' => 'title1',
- 'content' => 'content1',
- 'pubdate' => '2009-10-11',
- ),
- array(
- 'title' => 'title2',
- 'content' => 'content2',
- 'pubdate' => '2009-11 -11',
- )
- );
// Attribute array
- $attribute_array = array(
- 'title' => array(
- 'size' => 1
- )
- ) ;
// Create an XML document and set the XML version and encoding. .
- $dom=new DomDocument('1.0', 'utf-8');
// Create 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) {
- // Create element
- $$key = $dom ->createElement($key);
- $item->appendchild($$key);
// Create element value
- $text = $dom->createTextNode($val );
- $$key->appendchild($text);
if (isset($attribute[$key])) {
- // If there are related attributes in this field, they need to be set
- foreach ($attribute[$key] as $akey => $row) {
- // Create attribute node
- $$akey = $dom->createAttribute($akey);
- $$key->appendchild($ $akey);
// Create attribute value node
- $aval = $dom->createTextNode($row);
- $$akey->appendChild($aval);
- }
- } // end if
- }
- } // end if
- } // end function
- ?>
-
Copy code
Method 3, use XMLWriter class to create XML file1 2 Next Last Page
|