sql >> Base de Datos >  >> RDS >> Mysql

Cómo agregar y cambiar etiquetas XML en PHP

De su código:

while ($row = mysql_fetch_array($result1)) 

Debería poder obtener una matriz con la siguiente información (o algo similar):

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

Para obtener el XML, suelo usar SimpleXMLElement. Ejemplo a continuación de cómo obtengo la siguiente estructura:

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