135

I am having a problem accessing the @attribute section of my SimpleXML object. When I var_dump the entire object, I get the correct output, and when I var_dump the rest of the object (the nested tags), I get the correct output, but when I follow the docs and var_dump $xml->OFFICE->{'@attributes'}, I get an empty object, despite the fact that the first var_dump clearly shows that there are attributes to output.

Anyone know what I am doing wrong here/how I can make this work?

4

10 に答える 10

147

これを試して

$xml->attributes()->Token
于 2012-09-26T10:57:47.720 に答える
93

XML ノードで attributes() 関数を呼び出すことにより、XML 要素の属性を取得できます。その後、関数の戻り値を var_dump できます。

詳細については、php.net http://php.net/simplexmlelement.attributesを参照してください。

そのページのコード例:

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
于 2009-10-30T20:37:35.433 に答える
64

下のようになるのに何度も使ったのです@attributesが、少し長かったです。

$att = $xml->attributes();
echo $att['field'];

より簡単になるはずで、次の形式の属性を一度にのみ取得できます。

標準的な方法 - 配列アクセス属性 (AAA)

$xml['field'];

他の選択肢は次のとおりです。

ライト&クイックフォーマット

$xml->attributes()->{'field'};

間違ったフォーマット

$xml->attributes()->field;
$xml->{"@attributes"}->field;
$xml->attributes('field');
$xml->attributes()['field'];
$xml->attributes->['field'];
于 2013-09-04T14:45:38.740 に答える
43
$xml = <<<XML
<root>
<elem attrib="value" />
</root>
XML;

$sxml = simplexml_load_string($xml);
$attrs = $sxml->elem->attributes();
echo $attrs["attrib"]; //or just $sxml->elem["attrib"]

を使用しSimpleXMLElement::attributesます。

実のところ、SimpleXMLElementget_propertiesハンドラーには大きな問題があります。「@attributes」という名前のプロパティがないため、できません$sxml->elem->{"@attributes"}["attrib"]

于 2010-08-04T23:10:53.397 に答える
15

あなたはただ行うことができます:

echo $xml['token'];
于 2010-08-05T02:21:22.767 に答える
8

ただし、これらの属性のリストを探している場合は、XPath が役に立ちます。

print_r($xml->xpath('@token'));
于 2010-08-08T14:44:18.790 に答える
4

simplexml_load_file($file) の結果を JSON 構造に変換してデコードするのに役立ちました。

$xml = simplexml_load_file("$token.xml");
$json = json_encode($xml);
$xml_fixed = json_decode($json);

$try1 = $xml->structure->{"@attributes"}['value'];
print_r($try1);

>> result: SimpleXMLElement Object
(
)

$try2 = $xml_fixed->structure->{"@attributes"}['value'];
print_r($try2);

>> result: stdClass Object
(
    [key] => value
)
于 2016-02-12T12:53:28.217 に答える
3

残念ながら、私は PHP 5.5 のユニークなビルド (今のところ Gentoo で立ち往生しています) を持っています。

 $xml->tagName['attribute']

機能した唯一のソリューションでした。「Right & Quick」形式を含む、上記の Bora の方法をすべて試しましたが、すべて失敗しました。

これが最も簡単な形式であるという事実はプラスですが、他の人が言っているすべての形式を試してみると、私は正気ではないと考えるのが楽しくありませんでした.

その価値に満足しています(ユニークなビルドについて言及しましたか?)。

于 2015-01-08T14:47:01.567 に答える