【问题标题】:SimpleXML Access DataSimpleXML 访问数据
【发布时间】:2016-11-25 10:56:24
【问题描述】:

我有一个这样的 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<Data>
<Items>
    <Item Category="14" />
</Items>
<Events>
    <Event type="EventType">
        <Date>November 24, 2016</Date>
    </Event>
</Events>
</Data>

并且想在Item->Category中获取值“14”。

我试过这样:

echo $xml->Items->Item[0]->{@attributes}['Category'];

输出为空。

当我这样做的时候:

print_r($xml)

我明白了:

SimpleXMLElement Object ( [Items] => SimpleXMLElement Object ( [Item] => SimpleXMLElement Object ( [@attributes] => Array ( [Category] => 14 ) ) ) [Events] => SimpleXMLElement Object ( [Event] => SimpleXMLElement Object ( [@attributes] => Array ( [type] => EventType ) [Date] => November 24, 2016 ) ) )

然后我尝试了:

$p = xml_parser_create();
xml_parse_into_struct($p, $xml, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);

输出是:

Index array Array ( ) Vals array Array ( )

XML 是这样打开的:

$file="test.xml";


if (file_exists($file)) {
    $xml = simplexml_load_file($file);

【问题讨论】:

  • 谢谢。输出为空:-(
  • “Print_r($xml->Items->Item[0]->{@attributes});”的输出是“SimpleXMLElement 对象()”
  • 做这样的事情(第一个例子):-php.net/manual/en/function.xml-parse-into-struct.php
  • 输出为“索引数组数组()Vals数组数组()”:-(

标签: php xml simplexml


【解决方案1】:

您可以使用以下代码获取它:

$xml = simplexml_load_file('folder/yourfile');
$xmlselect = $xml->Data;

foreach($xmlselect AS $objekt)
{
      $items = $objekt->Items->Item;
        foreach ($items as $key) {
            $itemId= $key->attributes();
        }
}

也许对你有帮助!

【讨论】:

    猜你喜欢
    • 2011-03-25
    • 2013-12-23
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多