2015-07-20 47 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德文 –