PHP XMLReader xml:lang

时间:2015-07-20 13:09:57

标签: php xml

如何从此xml文件中读取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 =“de” - 标签和图像值。 有没有人有想法? Thanx: - )

更新:我像这样解析xml,但是如何得到这个值???

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

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

...

2 个答案:

答案 0 :(得分: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";
   }
}

答案 1 :(得分: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