XML标记内的变量值

时间:2015-08-21 04:09:36

标签: php xml

我想将$ album的值放入名为category的XML标记中。但我尝试的一切都是错的。我得到的最接近的是变量名$ album,但不是里面的数据。我是用PHP编写XML的新手。我尝试了各种串联和放大器。我看过这里提到的CDATA,但不知道我是应该使用它还是如何使用它。

<?php
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "password";
$dbname = "db";
@mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);


$sql = "SELECT * FROM responsivegallery_rgal";
$q   = mysql_query($sql) or die(mysql_error());

$album = $q['album_rgal'];
$category_tag = '"<category caption = ". $album .">"';

$xml = "<gallery>";
while($r = mysql_fetch_array($q)){


  $xml .= $category_tag ."</category>";
  $xml .= "<item>"; 
  $xml .= "<image>"."gallery_files/slides/".$r['image_rgal']."</image>";
  $xml .= "<thumb>"."gallery_files/slides/".$r['thumb_rgal']."</thumb>";  
  $xml .= "<caption>".$r['title_rgal']."</caption>";
  $xml .= "</item>";  
}
$xml .= "</gallery>";
$sxe = new SimpleXMLElement($xml);
$sxe->asXML("test.xml");
//$sxe->asXML("../gallery_files/gallery.xml");
?>

1 个答案:

答案 0 :(得分:1)

您错误地构建了循环,$q未被提取,因此['album_rgal']不存在。试试这个

<?php
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "password";
$dbname = "db";
@mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);


$sql = "SELECT * FROM responsivegallery_rgal";
$q   = mysql_query($sql) or die(mysql_error());

$xml = "<gallery>";
while($r = mysql_fetch_array($q)){
  $xml .= '<category caption="'. $r['album_rgal'] .'"></category>';
  $xml .= "<item>";
  $xml .= "<image>"."gallery_files/slides/".$r['image_rgal']."</image>";
  $xml .= "<thumb>"."gallery_files/slides/".$r['thumb_rgal']."</thumb>";  
  $xml .= "<caption>".$r['title_rgal']."</caption>";
  $xml .= "</item>";  
}
$xml .= "</gallery>";
$sxe = new SimpleXMLElement($xml);
$sxe->asXML("test.xml");
//$sxe->asXML("../gallery_files/gallery.xml");
?>

你的连接也没了。

$category_tag = '"<category caption = ". $album .">"';

本来是

$category_tag = '"<category caption = "'. $album .'">"';