使用循环填充 XML

发布于 2024-11-28 06:27:51 字数 1474 浏览 0 评论 0原文

我试图找出一种更动态地填充 XML 对象的方法,而不必不断更改节点的名称。我有一些与此类似的代码:

编辑:将数据更改为与实际数据库结构内联:

$query = ("Select order_id, created_on, updated_on, status from table orders;");

// Execute query
$result = mysql_query($query, $link) or die("Could not complete database query");

// Populate array
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray)); 

  $doc = new DOMDocument();
  $doc->formatOutput = true; 

  $r = $doc->createElement( "data" );
  $doc->appendChild( $r ); 

  foreach( $resultArray as $record )
  {
  $b = $doc->createElement( "record" ); 

  $record1 = $doc->createElement( "Order" );
  $record1->appendChild(
  $doc->createTextNode( $record['order_id'] )
  );
  $b->appendChild( $record1 ); 

  $record2 = $doc->createElement( "Created" );
  $record2->appendChild(
  $doc->createTextNode( $record['created_on'] )
  );
  $b->appendChild( $record2 ); 

  $record3 = $doc->createElement( "Updated" );
  $record3->appendChild(
  $doc->createTextNode( $record['updated_on'] )
  );
  $b->appendChild( $record3 );

  $record4 = $doc->createElement( "Status" );
  $record4->appendChild(
  $doc->createTextNode( $record['status'] )
  );
  $b->appendChild( $record4 );

  $r->appendChild( $b );
  } 

  echo $doc->saveXML();

// Close connection
mysql_close($link);

这很好,但是如果我想在查询中添加第三列,我还必须将其添加到循环中。我确信有更好的方法来实际做到这一点。

有什么建议吗?

谢谢。

I'm trying to figure out a way to populate an XML object more dynamically without having to constantly change the name of the nodes. I some code similar to this:

EDIT: Changed the data to be inline with actual db structure:

$query = ("Select order_id, created_on, updated_on, status from table orders;");

// Execute query
$result = mysql_query($query, $link) or die("Could not complete database query");

// Populate array
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray)); 

  $doc = new DOMDocument();
  $doc->formatOutput = true; 

  $r = $doc->createElement( "data" );
  $doc->appendChild( $r ); 

  foreach( $resultArray as $record )
  {
  $b = $doc->createElement( "record" ); 

  $record1 = $doc->createElement( "Order" );
  $record1->appendChild(
  $doc->createTextNode( $record['order_id'] )
  );
  $b->appendChild( $record1 ); 

  $record2 = $doc->createElement( "Created" );
  $record2->appendChild(
  $doc->createTextNode( $record['created_on'] )
  );
  $b->appendChild( $record2 ); 

  $record3 = $doc->createElement( "Updated" );
  $record3->appendChild(
  $doc->createTextNode( $record['updated_on'] )
  );
  $b->appendChild( $record3 );

  $record4 = $doc->createElement( "Status" );
  $record4->appendChild(
  $doc->createTextNode( $record['status'] )
  );
  $b->appendChild( $record4 );

  $r->appendChild( $b );
  } 

  echo $doc->saveXML();

// Close connection
mysql_close($link);

This is fine, but if I want to add a 3rd column in the query I have to also add it to the loop. I'm sure there is a better way to actually do this.

Any advice?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

人间不值得 2024-12-05 06:27:51

也许我写的这个类会对您有所帮助...

<?PHP
class ArrayTo
{
    protected static function array2xml($xml, $arr, $elements)
    {
        foreach($arr as $key => $value)
        {
            $element = isset($elements[0]) ? $elements[0] : $key;
            if(is_array($value))
            {
                $xml->startElement($element);
                self::array2xml($xml, $value, array_slice($elements, 1));
                $xml->endElement();
                continue;
            }
            $xml->writeElement($element, $value);
            $elements = array_slice($elements, 1);
        }
    }

    public static function xml($arr, $root = 'root', $elements = Array(), $version = '1.0', $encoding = 'UTF-8')
    {
        $xml = new XMLWriter();
        $xml->openMemory();
        $xml->startDocument($version, $encoding);
        $xml->startElement($root);
        self::array2xml($xml, $arr, $elements);
        $xml->endElement();
        return $xml->outputMemory(true);
    }
}
?>

如何使用它...

$data = array(
    "column1" => "im column 1",
    "column2" => "im column 2",
    "column3" => "im column 3",
    "column4" => "im column 4",
    "column5" => "im column 5",
);

echo ArrayTo::xml($data, 'table');

// output
<?xml version="1.0" encoding="UTF-8"?>
<table>
    <column1>im column 1</column1>
    <column2>im column 2</column2>
    <column3>im column 3</column3>
    <column4>im column 4</column4>
    <column5>im column 5</column5>
</table>

您还可以使用第三个参数 $elements 用自定义元素覆盖该级别的 $key。例如...

echo ArrayTo::xml($data, 'table', array('COLUMN_1', 'COLUMN_2'));

// output
<?xml version="1.0" encoding="UTF-8"?>
<table>
    <COLUMN_1>im column 1</COLUMN_1>
    <COLUMN_2>im column 2</COLUMN_2>
    <column3>im column 3</column3>
    <column4>im column 4</column4>
    <column5>im column 5</column5>
</table>

Maybe this class I wrote will help you out...

<?PHP
class ArrayTo
{
    protected static function array2xml($xml, $arr, $elements)
    {
        foreach($arr as $key => $value)
        {
            $element = isset($elements[0]) ? $elements[0] : $key;
            if(is_array($value))
            {
                $xml->startElement($element);
                self::array2xml($xml, $value, array_slice($elements, 1));
                $xml->endElement();
                continue;
            }
            $xml->writeElement($element, $value);
            $elements = array_slice($elements, 1);
        }
    }

    public static function xml($arr, $root = 'root', $elements = Array(), $version = '1.0', $encoding = 'UTF-8')
    {
        $xml = new XMLWriter();
        $xml->openMemory();
        $xml->startDocument($version, $encoding);
        $xml->startElement($root);
        self::array2xml($xml, $arr, $elements);
        $xml->endElement();
        return $xml->outputMemory(true);
    }
}
?>

How to use it...

$data = array(
    "column1" => "im column 1",
    "column2" => "im column 2",
    "column3" => "im column 3",
    "column4" => "im column 4",
    "column5" => "im column 5",
);

echo ArrayTo::xml($data, 'table');

// output
<?xml version="1.0" encoding="UTF-8"?>
<table>
    <column1>im column 1</column1>
    <column2>im column 2</column2>
    <column3>im column 3</column3>
    <column4>im column 4</column4>
    <column5>im column 5</column5>
</table>

You can also use the third argument $elements to override the $key at the level with a custom element. For exmple...

echo ArrayTo::xml($data, 'table', array('COLUMN_1', 'COLUMN_2'));

// output
<?xml version="1.0" encoding="UTF-8"?>
<table>
    <COLUMN_1>im column 1</COLUMN_1>
    <COLUMN_2>im column 2</COLUMN_2>
    <column3>im column 3</column3>
    <column4>im column 4</column4>
    <column5>im column 5</column5>
</table>
温折酒 2024-12-05 06:27:51

你可以这样做:

$column_num = 1;
foreach ( $record as $r_key => $r_value )
{
    if (!preg_match('/_Column$/', $r_key)
        continue;

    $xml_record = $doc->createElement( "Column".$column_num );
    $xml_record->appendChild(
            $doc->createTextNode( $r_value )
        );
    $b->appendChild( $xml_record ); 
    $column_num++;
}

当然,你没有给我们确切的数据库结构,所以我假设你想要添加的列以 _Column 结尾(这就是为什么有 !preg_match( '/_Column$/', $r_key) )。如果您想要所有列,只需删除循环开头的这两行即可。

编辑:该死,我晚了 16 秒:<

You can do:

$column_num = 1;
foreach ( $record as $r_key => $r_value )
{
    if (!preg_match('/_Column$/', $r_key)
        continue;

    $xml_record = $doc->createElement( "Column".$column_num );
    $xml_record->appendChild(
            $doc->createTextNode( $r_value )
        );
    $b->appendChild( $xml_record ); 
    $column_num++;
}

Of course, you have not given us the exact DB structure, so I have assumed that the columns you want to add are ending with _Column (that's why there's that !preg_match('/_Column$/', $r_key) ). If you want all columns, just remove those 2 lines at the start of the loop.

EDIT: damn, I was 16 seconds too late :<

如梦亦如幻 2024-12-05 06:27:51

我会做类似的事情:

$elemColMap = array(
    'Column1' => 'First_Column',
    'Column2' => 'Second_Column',
);

foreach( $resultArray as $record )
{
    $b = $doc->createElement( "record" ); 

    foreach($elemColMap as $xmlElem => $dbCol) {
        $record1 = $doc->createElement( $xmlElem );
        $record1->appendChild(
            $doc->createTextNode( $record[$dbCol] )
        );
        $b->appendChild( $record1 );        
    }

    $r->appendChild( $b );  
} 

I would do something like that:

$elemColMap = array(
    'Column1' => 'First_Column',
    'Column2' => 'Second_Column',
);

foreach( $resultArray as $record )
{
    $b = $doc->createElement( "record" ); 

    foreach($elemColMap as $xmlElem => $dbCol) {
        $record1 = $doc->createElement( $xmlElem );
        $record1->appendChild(
            $doc->createTextNode( $record[$dbCol] )
        );
        $b->appendChild( $record1 );        
    }

    $r->appendChild( $b );  
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文