我正在使用php创建XML到SQL文件,但只希望我的脚本处理XML文档中的第一个条目
$xmlObject = $xmlDoc->getElementsByTagName('PlaylistEntry');
输入我想要的特定路径
/Playlist/PlaylistEntry[1]/Title[1]/text()
不会产生结果。
有什么建议吗?
编辑:
$xmlDoc = new DOMDocument();
$xmlDoc->load("file.xml");
$mysql_hostname = "";
$mysql_user = "";
$mysql_password = "";
$mysql_database = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Error");
mysql_select_db($mysql_database, $bd) or die("Error");
$xmlObject = $xmlDoc->getElementsByTagName('PlaylistEntry');
$itemCount = $xmlObject->length;
for ($i=0; $i < $itemCount; $i++){
$Title = $xmlObject->item($i)->getElementsByTagName('Title')->item(0)->childNodes->item(0)->nodeValue;
$sql = "INSERT INTO `nowplaying` (Title) VALUES ('$Title')";
mysql_query($sql);
print "Finished Item $Title<br/>";
}
的xml:
<Playlist>
<Refresh>41</Refresh>
<PlaylistEntry>
<Title>Tongue Tied</Title>
<Artist>Grouplove</Artist>
<Album>Never Trust A Happy Song</Album>
<ECommerceURL/>
<FileName>02_Tongue_Tied.mp3</FileName>
<trackType/>
<desc/>
<clickThruURL/>
<visualURL>
id=14245829|img=http://upload.wikimedia.org/wikipedia/en/f/f9/GrouploveTongueTied.jpg
</visualURL>
<Seconds>218</Seconds>
</PlaylistEntry>
<PlaylistEntry>
<Title>Holy Roller Novocaine</Title>
<Artist>Kings of Leon</Artist>
<Album>Kings of Leon EP</Album>
<ECommerceURL/>
<FileName>03_Holy_Roller_Novocaine.mp3</FileName>
<trackType/>
<desc/>
<clickThruURL/>
<visualURL>
id=18144083|img=http://upload.wikimedia.org/wikipedia/en/8/86/Holyrollernovacaine.jpg
</visualURL>
<Seconds>257</Seconds>
</PlaylistEntry>
<PlaylistEntry>
...
答案 0 :(得分:0)
替换
$xmlObject = $xmlDoc->getElementsByTagName('PlaylistEntry');
$itemCount = $xmlObject->length;
for ($i=0; $i < $itemCount; $i++){
$Title = $xmlObject->item($i)->getElementsByTagName('Title')->item(0)->childNodes->item(0)->nodeValue;
使用xpath
代码$xpath = new DOMXpath($xmlDoc);
$elements = $xpath->query("/Playlist/PlaylistEntry/Title/text()");
if (!is_null($elements))
foreach ($elements as $element)
$Title = $element->wholeText;
答案 1 :(得分:0)
谢谢splash58!
我开始工作了!
以下是我最终的结果:
$xpath = new DOMXpath($xmlDoc);
$elements = $xpath->query("/Playlist/PlaylistEntry[1]");
if (!is_null($elements))
foreach ($elements as $element)
$Title = $xpath->query("/Playlist/PlaylistEntry[1]/Title[1]/text()", $element)->item(0)->nodeValue;
$Artist = $xpath->query("/Playlist/PlaylistEntry[1]/Artist[1]/text()", $element)->item(0)->nodeValue;
$sql = "INSERT INTO `nowplaying` (Title, Artist) VALUES ('$Title', '$Artist')";
再次感谢有用的推动:)