2012-09-06 192 views
-1

我得到這個XML:Xpath的獲取特定的屬性值

  <shipping_line> 
       <article id="960382" quantity="500" /> 
       <article id="960560" quantity="150" /> 
       <article id="960426" quantity="250" /> 
       <article id="1177" quantity="100" > 
        <product>5500070000126273</product> 
        <product>5500070000126264</product> 
        <product>5500070000126255</product> 
        <product>5500070000126246</product> 
        <product>5500070000126237</product> 
       </article> 
      </shipping_line> 

,我訪問文章內容atributes ID和quantity這樣的:

$atrs = $xml->xpath('//article[not(node())]/@quantity | //article[not(node())]/@id'); 

現在我想進入兩個值我做了這樣的foreach:

  foreach ($atrs as $id => $val) { 

       error_log(print_r($val , true)); 

      } 

而我的錯誤日誌顯示此:

SimpleXMLElement Object\n(\n [@attributes] => Array\n  (\n   [id] => 960382\n  )\n\n)\n 
SimpleXMLElement Object\n(\n [@attributes] => Array\n  (\n   [quantity] => 500\n  )\n\n)\n 
SimpleXMLElement Object\n(\n [@attributes] => Array\n  (\n   [id] => 960560\n  )\n\n)\n 
SimpleXMLElement Object\n(\n [@attributes] => Array\n  (\n   [quantity] => 150\n  )\n\n)\n 
SimpleXMLElement Object\n(\n [@attributes] => Array\n  (\n   [id] => 960426\n  )\n\n)\n 
SimpleXMLElement Object\n(\n [@attributes] => Array\n  (\n   [quantity] => 250\n  )\n\n)\n 

我怎麼能進入兩個值,這樣我就可以使用這樣的函數 someFunctionUsing2Values($article_no , $quantity)

回答

2

這是我會怎麼做:

$xml = new SimpleXMLElement(' 
<shipping_line> 
    <article id="960382" quantity="500" /> 
    <article id="960560" quantity="150" /> 
    <article id="960426" quantity="250" /> 
    <article id="1177" quantity="100" > 
     <product>5500070000126273</product> 
     <product>5500070000126264</product> 
     <product>5500070000126255</product> 
     <product>5500070000126246</product> 
     <product>5500070000126237</product> 
    </article> 
</shipping_line>'); 

$nodes = $xml->xpath('//article[not(node())]'); 
foreach ($nodes as $node) 
{ 
    fn($node['id'], $node['quantity']); 
} 

function fn($id, $quantity) 
{ 
    echo "$id -> $quantity<br>"; 
} 
+2

現場例如:http://codepad.viper -7.com/Ug​​Vmco – j0k

+0

謝謝你這就是我需要測試的東西 –