我需要帮助通过php从我的sql数据库生成youtube id的简单xml文件。
期望的输出
<videos>
<youtube media="http://www.youtube.com/watch?v=_hTiRnqnvDs" autoplay="true"></youtube>
<youtube media="http://www.youtube.com/watch?v=5wx0GfbC0BA" autoplay="true"></youtube>
<youtube media="http://www.youtube.com/watch?v=ERGrSQoY5fs" autoplay="true"></youtube>
</videos>
我的输出
<videos>
<youtube media="http://www.youtube.com/watch?v=![CDATA[$value]]" autoplay="true"></youtube>
<youtube media="http://www.youtube.com/watch?v=![CDATA[$value]]" autoplay="true"></youtube>
<youtube media="http://www.youtube.com/watch?v=![CDATA[$value]]" autoplay="true"></youtube>
</videos>
这是我从数据库查询中获得的输出
SELECT `key`,`value` FROM `jr_jryoutube_item_key` WHERE `key` = "youtube_id"
结果:
---------- -----------
key value
---------- -----------
youtube_id 3VVAzFlmeWc
youtube_id Rr9SfJwctRg
youtube_id ocOZLHyOSZw
youtube_id n-rQDYNOCyA
youtube_id VaQlSnII-Hc
以下是我的尝试。它正在生成一个xml文件,但它没有读取youtube id。
error_reporting(E_ALL);
//database configuration
$_conf['jrCore_db_host'] = 'localhost';
$_conf['jrCore_db_port'] = '3306';
$_conf['jrCore_db_name'] = 'xxxxxx';
$_conf['jrCore_db_user'] = 'xxxxxx';
$_conf['jrCore_db_pass'] = 'xxxxxx';
//connect to host
$con = mysqli_connect($_conf['jrCore_db_host'],$_conf['jrCore_db_user'],$_conf['jrCore_db_pass']);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// select database
mysqli_select_db($con,$_conf['jrCore_db_name']);
echo "Connected successfully";
$myFile = "videos.xml";
$fh = fopen($myFile, 'wb') or die("can't open file");
$xml_txt .= '<videos>';
// $query is an array with your values
$query = "SELECT `key`,`value` FROM `jr_jryoutube_item_key` WHERE `key` = 'youtube_id'";
$result = mysqli_query($con,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($con));
}
if(mysqli_num_rows($result)>0)
{
while($result_array = mysqli_fetch_assoc($result))
{
//loop through each key,value pair in row
foreach($result_array as $key => $value)
{
//embed the SQL data in a CDATA element to avoid XML entity issues
$xml_txt .= '<youtube media="http://www.youtube.com/watch?v=![CDATA[$value]]" autoplay="true">';
$xml_txt .= '</youtube>';
}
}
}
$xml_txt .= '</videos>';
fwrite($fh, $xml_txt);
fclose($fh);
您不应该对 xml 文件使用 fwrite,有更方便的方法可用。例如,您可以使用simple_xml:
$videoxml = new SimpleXMLElement("<videos></videos>");
您正在 while 循环中运行 foreach 循环,这是错误的。只需运行 while 循环并从结果集中选取值:
$url = 'http://www.youtube.com/watch?v=' . $result_array['value'];
$video = $videoxml->addChild('youtube');
$video->{0} = $url;
$video->addAttribute('autoplay', 'true');
我希望我已经正确解释了您的代码,但据我所知,没有理由从数据库中选择"密钥",因为您不使用它。
带有循环的代码应如下所示:
$xml = new SimpleXMLElement("<videos></videos>");
foreach ($result as $row)
{
$url = 'http://www.youtube.com/watch?v=' . $row['value'];
$video = $xml->addChild('youtube');
$video->{0} = $url;
$video->addAttribute('autoplay', 'true');
}
$xml->saveXML('/path/to/file.xml')
请注意,我直接为标签提供了值,没有使用两个属性,也没有标签的内容。