簡體   English   中英

PHP XMLReader xml:lang

[英]PHP XMLReader xml:lang

如何從此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”的值-標記和圖像值。 有人有想法嗎??? 謝謝:-)

更新:我這樣解析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)); ... 

我認為應該這樣做。

$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";
   }
}

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

$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM