提问人:Rediska 提问时间:10/23/2023 更新时间:10/24/2023 访问量:77
如何使用PHP获取XML元素的所有唯一值?
How to get all unique values of XML elements using PHP?
问:
我有一个XML文件。
$xml = simplexml_load_file('example.com');
它看起来像这样:
SimpleXMLElement {#1635 ▼
+"@attributes": array:1 [▶]
+"shop": SimpleXMLElement {#1615 ▼
+"categories": SimpleXMLElement {#1616 ▶}
+"currencies": SimpleXMLElement {#1617 ▶}
+"offers": SimpleXMLElement {#1618 ▼
+"offer": array:1513 [▼
0 => SimpleXMLElement {#1657 ▶}
1 => SimpleXMLElement {#1658 ▶}
2 => SimpleXMLElement {#1659 ▶}
3 => SimpleXMLElement {#1660 ▶}
...
120158 => SimpleXMLElement {#3169 …10}
]
}
}
}
我需要报价的所有元素。 通过这种方式,我选择了我需要的元素的路径:
$xml = $xml->shop->offers->offer;
我明白了:
SimpleXMLElement {#995 ▼
+"@attributes": array:2 [▼
"id" => "552550582"
"available" => "true"
]
+"categoryId": "3e71f0c49b"
+"description": """
text
"""
+"modified_time": "1697969563"
+"name": "Long-sleeve shirt"
+"param": array:3 [▼
0 => SimpleXMLElement {#1617 ▶}
1 => SimpleXMLElement {#1618 ▼
+"@attributes": array:1 [▼
"name" => "gender"
]
+"0": "female"
}
2 => SimpleXMLElement {#1619 ▼
+"@attributes": array:1 [▼
"name" => "color"
]
+"0": "Black"
}
]
+"picture": array:8 [▶]
+"price": "6490.0"
+"url": "example.com ▶"
}
如何从每个选件及其唯一唯一值中获取所有可能的元素。我想看到它是这样的:
$offerValues = [
'categoryId' = [1,2,3,10...],
'param@gender' = ['female', 'male'],
'param@color' = ['black', 'white', 'red'],
...
]
我刚刚开始学习 CML,希望得到任何帮助!
答:
0赞
Rediska
10/24/2023
#1
$color = $xml->xpath('//shop/offers/offer/param[@name = "color"][not(. = following::param[@name = "color"]/.)]');
评论
0赞
Kent Kostelac
10/24/2023
感谢您对 Stack Overflow 社区的贡献。这可能是一个正确的答案,但提供代码的额外解释,以便开发人员能够理解你的推理,这将是非常有用的。这对于不熟悉语法或难以理解概念的新开发人员特别有用。为了社区的利益,您能否编辑您的答案以包含其他详细信息?
评论
$xml->shop->offers->offer
是一个数组;你能添加你正在使用的代码吗?$color = $xml->xpath('//shop/offers/offer/param[@name = "color"]');
$xml->shop->offers->offer
foreach($xml->shop->offers->offer as $offer