2017-05-14 44 views
0

源XML是:simplexml_load_string獲取屬性

<attributeGroup id="999" name="Information"> 
    <attribute id="123" name="Manufacturer">Apple</attribute> 
    <attribute id="456" name="Model">iPhone</attribute> 
</attributeGroup> 

代碼:

$xml = simplexml_load_string($xml); 
print_r($xml); 

輸出:

SimpleXMLElement Object 
(
    [@attributes] => Array 
     (
      [id] => 999 
      [name] => Information 
     ) 

    [attribute] => Array 
     (
      [0] => Apple 
      [1] => iPhone 
     ) 

) 

我如何也可爲g等它返回標籤attribute idname

回答

0

你可以這樣使用屬性屬性來訪問它:

$x = simplexml_load_string($xml); 
$g = $x->attributeGroup; 
foreach($g->xpath("//attribute") as $attr){ 
    var_dump((string)$attr->attributes()->id); 
    var_dump((string)$attr->attributes()->name); 
    var_dump((string)$attr); // for text value 
} 
+0

謝謝。這工作,但我怎麼也可以在同一個數組中獲得文本值?所以它會顯示ID,名稱和文本值。 – user2029890

+0

更新了您的請求的代碼 – abeyaz

0

Try this code snippet here

<?php 
ini_set('display_errors', 1); 
$string=' <attributeGroup id="999" name="Information"> 
       <attribute id="123" name="Manufacturer">Apple</attribute> 
       <attribute id="456" name="Model">iPhone</attribute> 
    </attributeGroup> 
'; 

$xml = simplexml_load_string($string); 
$result=array(); 
foreach($xml->xpath("//attribute") as $attr) 
{ 
    $result[(string)$attr->attributes()->id]= (string) $attr->attributes()->name; 
} 
print_r($result); 

輸出:

Array 
(
    [123] => Manufacturer 
    [456] => Model 
) 
0

所以很多過於複雜的答案的東西,是非常清楚地顯示在PHP manu中人在這裏:http://php.net/manual/en/simplexml.examples-basic.php

你只需要做到這一點:

$sx = simplexml_load_string($xml); 
// $sx is the outer tag of your XML; in your example <attributeGroup> 
// Access child tags with -> 
foreach($sx->attribute as $attr){ 
    // Access attributes with ['...'] 
    var_dump((string)$attr['id']); 
    // Access text and CDATA content with (string) 
    var_dump((string)$attr); 
}