【问题标题】:xml array doesn't workxml 数组不起作用
【发布时间】:2015-03-27 19:40:38
【问题描述】:

我有这个 xml 文件:

<product    
<EANCode EAN="5053973641331"/>

我用这个来赋值

  $prodean=$XMLarray['Product']['EANCode']['@attributes'];
  $ean1[0]=$prodean['EAN'];

它工作正常。 但是当我有更多的 EAN 值时,例如

<EANCode EAN="5053973641331"/>
<EANCode EAN="7301433035830"/>
<EANCode EAN="0730143303583"/>
<EANCode EAN="0730143303378"/>
<EANCode EAN="5053118731828"/>
<EANCode EAN="5053973635132"/>

它不起作用。 我的错在哪里?

我总是想要第一个 EAN 值。如果在 xml 文件中只有一个 EAN 值,我有它,但如果有两个或更多值,我有 $ean1[0]

的 NULL

【问题讨论】:

  • 究竟是什么不起作用?预期和实际行为是什么?
  • @JaroslawPawlak 我总是想要第一个 EAN 值。如果在 xml 文件中只有一个 EAN 值,我有它,但如果有两个或更多值,我有 $ean1[0] 的 NULL
  • 所以在你的问题中描述它,因为目前,很难说出你在问什么。
  • $prodean=$XMLarray['Product']['EANCode'][0]['@attributes'];工作吗?
  • @JaroslawPawlak 它反过来工作。如果我有两个值可以正常工作,只有一个不起作用。

标签: php arrays xml


【解决方案1】:

这是一个简短的例子。我已经测试了你的代码,它有点棘手。

$xml = '<products>
<EANCode EAN="5053973641331"/>
<EANCode EAN="7301433035830"/>
<EANCode EAN="0730143303583"/>
<EANCode EAN="0730143303378"/>
<EANCode EAN="5053118731828"/>
<EANCode EAN="5053973635132"/>
</products>';

$XMLarray = simplexml_load_string($xml);
foreach($XMLarray->EANCode as $xml) {
    echo $xml->attributes()['EAN']."<br>";
}

所以你的 xml 例子:

http://data.icecat.biz/export/freexml.int/IT/8952561.xml

我的代码不起作用,因为您有一个名为“产品”的节点,因此您应该先访问它们。那么应该可以获取数据了。

$XMLarray = simplexml_load_string(file_get_contents("test.xml"));
foreach($XMLarray->Product->EANCode as $xml) {
    echo $xml->attributes()['EAN']."<br>";
}

我已将您的 xml 放入文件 test.xml 并且该代码正在运行。

【讨论】:

  • 我试过了,它对我不起作用。也许是因为我之前有另一个 xmlarray? $prod=$XMLarray['Product']['@attributes'];
  • 如果您有其他结构,则代码无法正常工作,但您可以采用它来解决您的问题;)
  • 当您加载 XML 时,您位于第一个元素中,您必须遍历所有子元素。然后您可以使用 attributes 函数访问该值。
  • 好的,但是你的代码和这个没有区别: foreach($XMLarray['Product']['EANCode'] as $test1){ $ean1[$i]=$test1[ '@attributes']['EAN']; } 对吗?
  • 也许我的问题出在这种类型的阵列上? $xml = simplexml_load_string($util->getJson($_POST['linkXML'])); $json = json_encode($xml); $XMLarray = json_decode($json,TRUE);
【解决方案2】:

试试这个:

$file = 'http://openIcecat-xml:freeaccess@data.icecat.biz/export/freexml.int/IT/8952561.xml';
$xml = simplexml_load_file($file);
// get first "EANCode" node and its "EAN" attribute
echo $xml->Product->EANCode[0]['EAN'];

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-27
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多