[英]Extracting Certain XML Elements with PHP SimpleXML
I am having some problems parsing this piece of XML using SimpleXML. 我在使用SimpleXML解析这段XML时遇到一些问题。 There is always only one Series element, and a variable number of Episode elements beneath.
始终只有一个Series元素,下面有可变数量的Episode元素。 I want to parse XML so I can store the Series data in one table, and all the Episode data in another table.
我想解析XML,以便可以将Series数据存储在一个表中,并将所有Episode数据存储在另一个表中。
XML: XML:
<Data>
<Series>
<id>80348</id>
<Genre>|Action and Adventure|Comedy|Drama|</Genre>
<IMDB_ID>tt0934814</IMDB_ID>
<SeriesID>68724</SeriesID>
<SeriesName>Chuck</SeriesName>
<banner>graphical/80348-g.jpg</banner>
</Series>
<Episode>
<id>935481</id>
<Director>Robert Duncan McNeill</Director>
<EpisodeName>Chuck Versus the Third Dimension 2D</EpisodeName>
<EpisodeNumber>1</EpisodeNumber>
<seasonid>27984</seasonid>
<seriesid>80348</seriesid>
</Episode>
<Episode>
<id>935483</id>
<Director>Robert Duncan McNeill</Director>
<EpisodeName>Buy More #15: Employee Health</EpisodeName>
<EpisodeNumber>2</EpisodeNumber>
<seasonid>27984</seasonid>
<seriesid>80348</seriesid>
</Episode>
</Data>
When I attempt to access just the first Series element and child nodes, or iterate through the Episode elements only it does not work. 当我尝试仅访问第一个Series元素和子节点,或仅对Episode元素进行迭代时,它不起作用。 I have also tried to use DOMDocument with SimpleXML, but could not get that to work at all.
我还尝试过将DOMDocument与SimpleXML一起使用,但根本无法正常工作。
PHP Code: PHP代码:
<?php
if(file_exists('en.xml'))
{
$data = simplexml_load_file('en.xml');
foreach($data as $series)
{
echo 'id: <br />' . $series->id;
echo 'imdb: <br />' . $series->IMDB_ID;
}
}
?>
Output: 输出:
id:80348
imdb:tt0934814
id:935481
imdb:
id:1534641
imdb:
I just discovered the stupid mistake I was making. 我刚刚发现自己犯的愚蠢错误。
The PHP code should have been like this: PHP代码应该是这样的:
<?php
if(file_exists('en.xml'))
{
$data = simplexml_load_file('en.xml');
foreach($data->Series as $series)
{
echo 'id: <br />' . $series->id;
echo 'imdb: <br />' . $series->IMDB_ID;
}
}
?>
The first time I tried this (and it did not work) I was using; 第一次尝试(但不起作用)时,我正在使用;
$data->series as $series
So it was a capital 'S' that was the issue. 因此,问题在于大写字母“ S”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.