2015-10-18 167 views
0

我需要執行一個API,它的響應是一個XML。 但是XML值在XML標籤內。php獲取xml內部標籤內容

例如

<example> 
<item productid = "1" productname = "xxx" cost = "5.3"/> 
<item productid = "2" productname = "yyy" cost = "4.0"/> 
<item productid = "3" productname = "zzz" cost = "1.75"/> 
</example> 

誰能告訴我,我怎樣才能,標籤之間移動,並得到elemnt值 例如:

example: 
item: 
    productid -> 1, 
    productname -> xxx, 
    cost -> 5.3 
item: 
    productid -> 2, 
    productname -> yyy, 
    cost -> 4.0 
item: 
    productid -> 3, 
    productname -> zzz, 
    cost -> 1.75 

感謝名單

回答

1

的XPath: http://php.net/manual/en/simplexmlelement.xpath.php

不需要atory,你可以得到所有的孩子並循環遍歷它們,但是XPath在真實世界的場景(你有多層次的XML節點)中更加通用,並且可讀性更強。

<?php 
$xmlStr = <<<END 
<example> 
<item productid = "1" productname = "xxx" cost = "5.3"/> 
<item productid = "2" productname = "yyy" cost = "4.0"/> 
<item productid = "3" productname = "zzz" cost = "1.75"/> 
</example> 
END; 
$xml = new SimpleXMLElement($xmlStr); 

$items = $xml->xpath("//example/item"); 

$out = array(); 
foreach($items as $x) { 
    $out [] = $x->attributes(); 
} 
1

或者你可以使用一個DOMElement

$doc = new DOMDocument(); 
$doc->load('domexample.xml'); 
$elements = $doc->getElementsByTagName('item'); 

$x = 0; 
foreach($elements as $element) 
{ 
    $results[$x]['productid'] = $element->getAttribute('productid'); 
    $results[$x]['productname'] = $element->getAttribute('productname'); 
    $results[$x]['cost'] = $element->getAttribute('cost'); 
    $x++; 
} 
0
<?php 

$file = "filename.xml"; 
$example = simplexml_load_file($file) or die("Error: Can't Open File"); 

$prodidz = array(); 
$prodnamez = array(); 
$costz = array(); 

foreach ($example->children() as $item) 
{ 
$prodidz[] = $item->attributes()->productid; 
$prodnamez[] = $item->attributes()->productname; 
$costz[] = $item->attributes()->cost; 
} 

?>