【问题标题】:how to obtain values from an XML doc [duplicate]如何从 XML 文档中获取值 [重复]
【发布时间】:2015-07-09 22:11:09
【问题描述】:

我有连接到 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 循环?

【问题讨论】:

标签: php xml api


【解决方案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 循环来遍历它。

【讨论】:

  • 我已将我的 print_r($xml) 添加到原始问题中。我无法弄清楚 foreach 循环。如果你能帮助我,将不胜感激。
  • 你得到一个数组对象尝试美化你的数组,你会得到这样的数组 SimpleXMLElement Object ( [list] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 8 [name] => #1 [subscriber_count] => 210 [display_name] => 显示名称) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] = > 9 [name] => #2 [subscriber_count] => 2242 [display_name] => Display name ) ) 现在遍历孩子并遍历它。如果您不确定遍历,那么我建议阅读数组遍历
  • 你可以试试 echo '
    '; print_r($xml);回声'
    ';这样它对您来说可读性更高,并且易于理解和遍历
【解决方案2】:

它会帮助你。

$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";
    }
}

【讨论】:

  • 我从 try { $listing... 粘贴了您的代码,但出现错误:PHP Parse error: syntax error, unexpected 'catch' (T_CATCH)
  • 我已经测试过了,对我来说效果很好。确保你有正确的副本。
  • 我没有文件 source = test.xml,它在 Madmimi Api 上。这就是它不起作用的原因吗?
  • @LTech 我已经更新了答案。
猜你喜欢
  • 2018-11-18
  • 1970-01-01
  • 2019-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-18
相关资源
最近更新 更多