19

抱歉,如果这似乎是一个简单的问题,但我已经开始在这上面扯头发了……

我有一个看起来像这样的 XML 文件...

<VAR VarNum="90">
  <option>1</option>
</VAR>

我正在尝试获取VarNum

到目前为止,我已经成功使用以下代码获取其他信息:

$xml=simplexml_load_file($file);
$option=$xml->option;

我只是无法获得 VarNum (我认为的属性值?)

谢谢!

4

4 回答 4

24

您应该能够使用SimpleXMLElement::attributes()

试试这个:

$xml=simplexml_load_file($file);
foreach($xml->Var[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}

这将显示第一个foo元素的所有名称/值属性。它是一个关联数组,因此您也可以这样做:

$attr = $xml->Var[0]->attributes();
echo $attr['VarNum'];
于 2009-08-10T19:47:02.430 回答
14

怎么用$xml['VarNum']

像这样 :

$str = <<<XML
<VAR VarNum="90">
  <option>1</option>
</VAR>
XML;

$xml=simplexml_load_string($str);
$option=$xml->option;

var_dump((string)$xml['VarNum']);

(我使用过simplexml_load_string是因为我已将您的 XML 粘贴到一个字符串中,而不是创建一个文件;在您的情况下,您所做的一切simplexml_load_file都很好!)

会得到你

string '90' (length=2)

使用 simpleXML,您可以使用数组语法访问属性。
你必须转换为一个字符串来获取值,而不是实例SimpleXMLElement

例如,请参阅手册中基本用法的示例 #5 :-)

于 2009-08-10T19:44:38.860 回答
3
[0] => Array
                (
                    [@attributes] => Array
                        (
                            [uri] => https://abcd.com:1234/abc/cst/2/
                        [id] => 2
                    )

                [name] => Array
                    (
                        [first] => abcd
                        [last] => efg
                    )

                [company] => abc SOLUTION
                [email] => abc@xyz.com
                [homepage] => WWW.abcxyz.COM
                [phone_numbers] => Array
                    (
                        [phone_number] => Array
                            (
                                [0] => Array
                                    (
                                        [main] => true
                                        [type] => work
                                        [list_order] => 1
                                        [number] => +919876543210
                                    )

                                [1] => Array
                                    (
                                        [main] => false
                                        [type] => mobile
                                        [list_order] => 2
                                        [number] => +919876543210
                                    )

                            )

                    )

                [photo] => Array
                    (
                        [@attributes] => Array
                            (
                                [uri] => https://abcd.com:1234/abc/cst/2/cust_photo/
                            )

                    )

            )

我应用了以下代码

$xml = simplexml_load_string($response);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
print_r($array);

但它没有使用完整我想要php中单个数组中的所有数据

于 2012-12-28T06:35:31.300 回答
0

试试这个

$xml->attributes()['YourPropertyName']; //check property case also
于 2020-11-15T19:39:49.917 回答