从XML文件中提取艺术家名称时,只显示1条记录

时间:2011-08-03 14:23:31

标签: php xml

我已经在堆栈上进行了搜索,但据我所知,没有问题或答案直接回答这个问题。

我的代码如下:

$xml_data = file_get_contents('http://www.test.co.uk/charts.xml');
$xml = new SimpleXMLElement($xml_data);

$artist = $xml->artists->artist->name;
echo $artist;

然而,当我运行此代码时,它只显示第一个艺术家名称,是否有任何人知道如何让它显示xml文件中的所有名称。

供您参考,xml文件的布局如下:

<artists_chart start="" end="">
<period>Past 7 days</period>
<artists>
<artist gid="">
<name>Name1</name>
<plays>51</plays>
<previous_plays>53</previous_plays>
</artist>
<artist gid="">
<name>Name2</name>
<plays>45</plays>
<previous_plays>97</previous_plays>
</artist>
<artist gid="">
<name>Name3</name>
<plays>41</plays>
<previous_plays>39</previous_plays>
</artist>
</artists>
</artists_chart>

感谢您提供任何帮助或指导。

3 个答案:

答案 0 :(得分:2)

foreach ($xml->artists->children() as $child)
{
  $artist = (string)$child->name;
  echo $artist;
}

答案 1 :(得分:1)

您需要使用xpath选择节点(艺术家/艺术家),然后迭代结果集。在http://php.net/manual/en/simplexmlelement.xpath.php

中很好地涵盖了XPath和PHP

具体到你的问题:

$xml_data = file_get_contents('http://www.test.co.uk/charts.xml');
$xml = new SimpleXMLElement($xml_data);

$artists = $xml->xpath('/artists/artist');
if($artists) foreach($artsts as $artist){
  echo $artist->name;
}

使用更新的代码进行编辑:

<?php

$xml_data = <<<XML
<artists_chart start="" end="">
  <period>Past 7 days</period>
  <artists>
    <artist gid="">
      <name>Name1</name>
      <plays>51</plays>
      <previous_plays>53</previous_plays>
    </artist>
    <artist gid="">
      <name>Name2</name>
      <plays>45</plays>
      <previous_plays>97</previous_plays>
    </artist>
    <artist gid="">
      <name>Name3</name>
      <plays>41</plays>
      <previous_plays>39</previous_plays>
    </artist>
  </artists>
</artists_chart>
XML;

$xml = new SimpleXMLElement($xml_data);

$artists = $xml->xpath('/artists_chart/artists/artist');
if($artists) foreach($artists as $artist){
  echo $artist->name.'<br />';
}
echo('<hr />');
// or
foreach($xml->artists->artist as $artist){
  echo $artist->name.'<br />';
}

答案 2 :(得分:0)

为您的代码添加如下内容:

error_reporting(E_ALL);
ini_set('display_errors', 1);
$xml_data = file_get_contents('http://www.test.co.uk/charts.xml');
....

你会看到:

Warning: SimpleXMLElement::__construct(): Entity: line 6: parser error : Entity 'copy' not defined in 
.......

编辑1

抱歉,此错误仅表示“禁止访问”。 但如果我将你的xml复制为文本 - 一切都适合我(并显示Name1)。