我需要帮助才能通过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);
答案 0 :(得分:0)
你不应该将fwrite用于xml文件,有更方便的方法可用。例如,您可以使用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');
我希望我能正确理解你的代码,但据我所知,我没有理由选择&#34; key&#34;来自DB,因为你没有使用它。
带循环的代码看起来应该是这样的:
$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')
请注意,我已直接给标签赋值,不使用标签的两个属性和内容。