Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Wie man XML-Tags in PHP hinzufügt und ändert

Aus Ihrem Code:

while ($row = mysql_fetch_array($result1)) 

Sie sollten in der Lage sein, ein Array mit den folgenden Informationen (oder etwas Ähnlichem) zu erhalten:

$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'
),
);

Um das XML zu erhalten, verwende ich normalerweise SimpleXMLElement. Beispiel unten, wie ich die folgende Struktur erhalte:

<?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());