2011-06-17 49 views
0

$ xml = simplexml_load_file($ file)から返されたオブジェクトがあります。私は 'location-id'と 'item-id'にアクセスしようとしていますが、これらの情報にアクセスする方法はわかりません。 1回だけネストすると、$ xml - > {'item-id'}のようなことをすることができますが、動作しないようです。これの構文は何ですか?フォーマットが不十分で申し訳ありません。それがブラウザでどのように返されたのですか。構文の質問:PHPオブジェクトへのアクセス

SimpleXMLElement Object (
    [item] => Array (
     [0] => SimpleXMLElement Object (
      [@attributes] => Array (
       [item-id] => AAA) 
      [locations] => SimpleXMLElement Object (
       [location] => SimpleXMLElement Object (
        [@attributes] => Array (
         [location-id] => 111 
        ) 
        [quantity] => 1 
        [pick-up-now-eligible] => false 
       ) 
      ) 
     ) 
     [1] => SimpleXMLElement Object 
      [@attributes] => Array (
       [item-id] => BBB 
      ) 
      [locations] => SimpleXMLElement Object (
       [location] => SimpleXMLElement Object (
        [@attributes] => Array (
         [location-id] => 111 
        ) 
        [quantity] => 1 
        [pick-up-now-eligible] => false 
       ) 
      ) 
     ) 
    ) 
) 

誰かがチャイムインしますか? TIA !!それはSimpleXMLをして属性にアクセスするには

$xml->item[0]->attributes('item-id'); 
$xml->item[0]->locations->location->attributes('item-id'); 

答えて

1

だろう

+0

salathe、ありがとう!これは完全に動作します! – musicliftsme

2

、配列風の構文を使用することができます。

$element['attribute_name']; 

SimpleXMLElement::attributes()の方法も利用できます。上記のようになります。

$element->attributes()->attribute_name; 

属性が(例えばblah:attribute_name)名前空間されている場合、あなたはattributes()メソッドに(接頭辞、またはURIなど)、その名前空間を提供することができます。

$element->attributes('blah', TRUE)->attribute_name; 
$element->attributes('http://example.org/blah')->attribute_name; 

詳細については、SimpleXML Basic Usageマニュアルページを参照してください。 、あなたが使用できる二<item>要素のitem-id属性を印刷するには、この個別の問題のために実際に上記を入れて


echo $xml->item[1]['item-id']; 

<item>要素とプリントオーバーループ以下の例それらの関連するitem-idと(最初の)location-idの値です。

foreach ($xml->item as $item) { 
    $location = $item->locations->location; 
    echo 'Item ID: ' . $item['item-id'] . "\n"; 
    echo 'Locations: ' . $location['location-id'] . "\n"; 
} 
+0

ちょっとマーク、これは動作していないようです。エラーはありませんが、何も表示されません。もう一度見ていただけますか? (コードを書式化してくれてありがとう!) – musicliftsme

+0

ところで、私はecho $ xml-> item [0] - > attributes( 'item-id')でブラウザに表示しようとしています。これは間違った方法でしょうか? – musicliftsme