如何从XML文档中获取值

时间:2015-04-30 09:21:32

标签: php xml api

我有连接API的PHP代码:

require(dirname(__FILE__) . '/MadMimi.class.php');
$mailer = new MadMimi('XXX.org', '000');
$lists = $mailer->Lists();
var_dump($lists);
foreach ($lists as $list) {
echo $list['name']; }

var_dump 以下列形式显示XML文档:

`string '<?xml version="1.0" encoding="UTF-8"?>
<lists>
  <list id="8" name="#1" subscriber_count="210" display_name="Display name"/>
  <list id="9" name="#2" subscriber_count="2242" display_name="Display name"/>`

...(长度= 2726)

但它只显示前几行。如何让它显示所有值?

此外,我正在尝试使用foreach循环打印特定值,但它无效,我收到错误:Invalid argument supplied for foreach()

如果foreach不起作用,我还能从XML文档中获取值吗?

如果我这样做

$xml=simplexml_load_string($lists) or die("Error: Cannot create object"); 
print_r($xml);

我明白了:

SimpleXMLElement Object ( [list] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 8 [name] => #1 [subscriber_count] => 210 [display_name] => Display name ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 9 [name] => #2 [subscriber_count] => 2242 [display_name] => Display name ) )

如何为此编写foreach循环?

2 个答案:

答案 0 :(得分:1)

我不确定您的XML是怎样的,但您可以在php中阅读XML:

$file = "path to XML";

$xml=simplexml_load_file($file) or die("Error: Cannot create object");
print_r($xml);

这将返回一个简单的XML对象。

如果您的XML包含子子项,那么您可以使用foreach循环来遍历它。

答案 1 :(得分:1)

它会帮助你。

$lists = '<?xml version="1.0" encoding="UTF-8"?>
<lists>
  <list id="8" name="#1" subscriber_count="210" display_name="Display name"/>
  <list id="9" name="#2" subscriber_count="2242" display_name="Display name"/>
</lists>';


$xml = simplexml_load_string($lists) or die("Error: Cannot create object");

foreach ($xml->children() as $child) {
     // List all the tags
    echo '<pre>';print_r($child);echo '</pre>';

    foreach($child->attributes() as $a => $b) {
    // list all the attributes
        echo $a,'="',$b,"\"\n";
    }
}