使用PHP从SQL表数据创建XML文件

使用PHP从SQL表数据创建XML文件,php,mysql,xml,Php,Mysql,Xml,我有这张桌子 rss( id serial, title varchar(25) not null, link text not null, description TEXT not null, imagename text ); 。。。我试图从使用php存储的数据创建一个xml文件 $db = mysqli_connect("localhost", "root", "", "s3382313"); $q = 'select * from rss'; $

我有这张桌子

rss(
    id serial,
    title varchar(25) not null,
    link text not null,
    description TEXT not null,
    imagename text
);
。。。我试图从使用php存储的数据创建一个xml文件

$db = mysqli_connect("localhost", "root", "", "s3382313");
$q = 'select * from rss';
$run = mysqli_query($db, $q);

if( $run && mysqli_num_rows( $run ) ) {
    $doc = new DOMDocument( '1.0' );
    $doc->formatOutput = true;
    $doc->preserveWhiteSpace = true;

    $root = $doc->createElement( 'data' );
    $doc->appendChild( $root );

    while( ( $fetch = mysqli_fetch_assoc( $run ) )!== false ) {
        $node = $doc->createElement( 'node' );
        $root->appendChild( $node );

        foreach( $fetch as $key => $value ) {
            createNodes( $key, $value, $doc, $node );
        }
    }
    $doc->save("thexmlfile.xml");
}

function createNodes( $key, $value, $doc, $node ) {
    $key = $doc->createElement( $key );
    $node->appendChild( $key );
    $key->appendChild( $doc->createTextNode( $value ) );
}
我收到这个错误:

警告:为第27行C:\xampp\htdocs\WeatherRadar\process\u XML.php中的foreach()提供的参数无效

第27行是:
foreach($key=>$value){


我该怎么办?

我认为您的
$fetch
被限定在一个过多的括号内,它目前只测试while条件的有效性

while((true != false)) { 
    //...
} 
因此,也要重写:

while( $fetch = mysqli_fetch_assoc( $run )) {
   /** $fetch will be scoped for the loop now **/
}

其次,对于调试,在迭代之前检查$fetch的内容很重要,因为它可能不是嵌套的结果集。

您应该检查变量$fetch.What print\r($fetch);正在输出什么?数组([id]=>1[title]=>test rss[link]=>test.link[description]=>test description[imagename]=>IMG\u 1667.jpg)在我发布的上述代码中,$fetch输出是‘Array([id]=>1[title]=>testrss[link]=>test.link[description]=>test description[imagename]=>IMG_1667.jpg)'对于您的行,$fetch输出为'1'仍然具有相同的值error@EJackson删除
!==false
,因为只要
$run
循环结束,while就会停止。