通过PHP和SimpleXML问题显示数据

问题描述 投票:0回答:2

我在这个网站上经历了很多SimpleXML问题。我的数据有点奇怪,我无法改变。我试图从我的数据中获取“Building1”和“Hostname1”之类的内容,因此我可以获取该数据并查找其他数据,然后显示它。

以下是我的数据示例:

    <?xml version='1.0' encoding='UTF-8'?>
<results preview = '0'>
    <result offset='0'>
        <field k='hostname'>
          <value h='1'><text>Hostname 1</text></value>
        </field>
        <field k='os'>
          <value><text>Windows 7</text></value>
        </field>        
        <field k='location'>
          <value h='1'><text>Building 1</text></value>
        <field>
    </result>
   <result offset='1'>
        <field k='hostname'>
          <value h='1'><text>Hostname 2</text></value>
        </field>
        <field k='os'>
          <value><text>Windows 10</text></value>
        </field>        
        <field k='location'>
          <value h='1'><text>Building 2</text></value>
        </field>
     </result>
........

以下是我试图看待它的方式:

$xml = simplexml_load_file(data.xml);
print_r($xml);    
$testArray = new SimpleXMLElement($xml);
$records = $testArray->results->result;
print_r($records);

出于某种原因,我无法弄清楚如何从xml元素中获取数据。如果有人能指出我正确的方向,我会很感激。我尝试了很多很多选择。谢谢-

php xml simplexml
2个回答
0
投票

这是一个非常常见的错误,但是如果你不知道你在寻找什么,那么很难发现:你在使用XML解析时得到的第一个对象是根元素,而不是代表文档的东西。

所以在你的情况下,$testArray是元素<results preview = '0'>,你想要$testArray->result而不是$testArray->results->result

顺便说一下,“testArray”是这个变量的一个坏名字 - 它不是一个数组,它是一个对象。


0
投票

我在文件中使用xml作为字符串

<?php
$sXmlString = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<results preview = "0">
    <result offset="0">
        <field k="hostname">
          <value h="1"><text>Hostname 1</text></value>
        </field>
        <field k="os">
          <value><text>Windows 7</text></value>
        </field>        
        <field k="location">
          <value h="1"><text>Building 1</text></value>
        </field>
    </result>
    <result offset="1">
        <field k="hostname">
          <value h="1"><text>Hostname 2</text></value>
        </field>
        <field k="os">
          <value><text>Windows 10</text></value>
        </field>        
        <field k="location">
          <value h="1"><text>Building 2</text></value>
        </field>
    </result>
</results>
EOF;

echo '<pre>';
$xml = simplexml_load_string($sXmlString);
print_r($xml);
echo '<hr/>';
echo count($xml->result);
echo '<hr/>';
foreach($xml->result as $report)
{
    var_dump($report);
    echo '<hr/>';
}

在代码中你可以看到$ xml它自我引用“结果”(或根)元素。您需要从根元素到子元素。 $xml->result将在结果集中给出结果对象,你需要像对象数组一样进行循环。

© www.soinside.com 2019 - 2024. All rights reserved.