2015-07-20 49 views
0

如何從此xml文件讀取xml:lang值?PHP XMLReader xml:lang

<Catalog><Products> 
 
<Product> 
 
<Id>123</Id> 
 
<Name xml:lang="en">name english product</Name> 
 
<Description xml:lang="en">desc xyz</Description> 
 
<Name xml:lang="de">name german</Name> 
 
<Description xml:lang="de">desc germa</Description> 
 
<Image num="1"><Url>pic.jpg</Url></Image> 
 
<Image num="2"><Url>pic2.jpg</Url></Image> 
 
</Product> 
 
<Product>...

我想要的XML值:LANG = 「德」 - 標籤和圖像值。 有沒有人有想法? Thanx :-)

更新:我解析這樣的XML,但我怎麼得到這個值?

$datei = "test.xml"; 
 
$z = new XMLReader; 
 
$z->open($datei); 
 
\t 
 
$doc = new DOMDocument; 
 
\t 
 
while ($z->read() && $z->name !== 'Product'); 
 

 
$i = 0; while ($z->name === 'Product') 
 
{ $i++; 
 
$node = simplexml_import_dom($doc->importNode($z->expand(), true)); 
 

 
...

+0

可能重複(http://stackoverflow.com/questions/3996444/xmllang-parse-in-php) – donald123

+0

都想要它的Xpath表達式?或者PHP函數來解析XML並提取數據? – Andre

+0

我已更新帖子... PHP函數? –

回答

0

我想這應該這樣做。

$simpleXml = new SimpleXMLElement(file_get_contents($datei)); 
foreach ($simpleXml->Products->Product as $product) { 
    $name = $product->xpath('Name[@xml:lang="en"]')[0]; 
    echo $name . "\n"; 
    foreach($product->Image as $img) { 
     echo $img->Url . "\n"; 
    } 
} 
+0

謝謝,這個工程很好:-) ...有沒有辦法從while循環讀取值?像這樣? $節點 - >名稱 - >屬性( '@ XML:LANG = 「EN」]')[0]; –

0

xpath使用許多resurses。您可以掃描它,並獲取所需的節點。在代碼中,您將看到如何獲取具有前綴的節點和屬性的名稱和值。

$simpleXml = new SimpleXMLElement(file_get_contents($datei))); 
foreach ($simpleXml->Products->Product as $products)  // list of nodes with same name 
    foreach($products as $product) {      // every node 
    if ($product->getName() === 'Image') {    // for image take child 
     echo $product->Url->getName() . " = " . $product->Url ."\n"; 
     $attrs = $product->attributes();     // Attribute without prefix 
     if(isset($attrs['num'])) echo " num = " . $attrs['num'] . "\n"; 
    } 
    else echo $product->getName() . " = " . $product ."\n"; 

    $attrs = $product->attributes('xml', true);   // if 2nd true, 1st is prefix 
    if(isset($attrs['lang'])) echo " lang = " . $attrs['lang'] . "\n"; 
} 

結果

Id = 123 
Name = name english product 
    lang = en 
Description = desc xyz 
    lang = en 
Name = name german 
    lang = de 
Description = desc germa 
    lang = de 
Url = pic.jpg 
    num = 1 
Url = pic2.jpg 
    num = 2 
[XML:郎解析在PHP]的
+0

好的,但我怎麼才能得到「德」名?或者圖像編號=「2」? –

+0

@Andreas Kleine我已經更新了沒有前綴的答案forattribute。但不要理解第一個 - 關於「德」名稱 – splash58

+0

嗨,非常感謝 - 我需要名稱德國 ...的價值如此:如果xml: lang = de $ myname = name德文 –