sql >> Databasteknik >  >> RDS >> Mysql

Hur man lägger till och ändrar XML-taggar i PHP

Från din kod:

while ($row = mysql_fetch_array($result1)) 

Du bör kunna få en array med följande information (eller något liknande):

$rows = array(
array(
    'channel' => 'channel1',
    'start'   => 'start1',
    'stop'   => 'stop1',        
    'title'  => 'title1',
    'subtitle' => 'subtitle1',
    'desc'    => 'desc1',
    'category' => 'category1'
),
array(
    'channel' => 'channel2',
    'start'   => 'start2',
    'stop'   => 'stop2',        
    'title'  => 'title2',
    'subtitle' => 'subtitle2',
    'desc'    => 'desc2',
    'category' => 'category2'
),
);

För att få XML använder jag vanligtvis SimpleXMLElement. Exempel nedan på hur jag får följande struktur:

<?xml version="1.0" encoding="utf-8"?>
<tv generator-info-name="www.mysite.com/xmltv">
<channel id="">
    <display-name>channel1</display-name>
    <programme channel="channel1" start="start1" stop="stop1">
        <title lang="en">title1</title>
        <sub-title lang="en">subtitle1</sub-title>
        <desc lang="en">desc1</desc>
        <category lang="en">category1</category>
    </programme>
</channel>
<channel id="">
    <display-name>channel2</display-name>
    <programme channel="channel2" start="start2" stop="stop2">
        <title lang="en">title2</title>
        <sub-title lang="en">subtitle2</sub-title>
        <desc lang="en">desc2</desc>
        <category lang="en">category2</category>
    </programme>
</channel>

<?php
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?><tv generator-info-name="www.mysite.com/xmltv"></tv>
XML;

$my_xml = new SimpleXMLElement($xml);

foreach($rows as $row) {
    $channel = $my_xml->addChild('channel');
    $channel->addAttribute('id', '');

    $channel->addChild('display-name', $row['channel']);

    $programme = $channel->addChild('programme');
    $programme->addAttribute('channel', $row['channel']);
    $programme->addAttribute('start', $row['start']);
    $programme->addAttribute('stop', $row['stop']); 

    $title = $programme->addChild('title', $row['title']);
    $title->addAttribute('lang', 'en');

    $sub_title = $programme->addChild('sub-title', $row['subtitle']);
    $sub_title->addAttribute('lang', 'en');

    $desc = $programme->addChild('desc', $row['desc']);
    $desc->addAttribute('lang', 'en');

    $category = $programme->addChild('category', $row['category']);
    $category->addAttribute('lang', 'en');  
}

print_r($my_xml->asXML());



  1. Behöver hjälp med att designa min fakturadb-struktur

  2. Underfråga i SELECT-satsen (MySQL)

  3. SQL Server 2005 ROW_NUMBER() utan ORDER BY

  4. SUBSTR() Funktion i Oracle