0

我正在尝试制作一个通用的简单 XML 到数组类型的脚本。

这个想法是检测哪些节点正在重复,这就是我需要循环的标签名称

例如

饲料 1:-

<carfeed>
<sometag>
<child>
Child content
</child>
</sometag>
<cars>
<car>
<name>Ford</name>
<color>Blue</color>
</car>
<car>
<name>Nissan</name>
<color>Red</color>
</car>
</cars>
</carfeed>

饲料2:-

<vehicles>
<vehicle>
<name>Ford</name>
<color>Blue</color>
<type>Pickup</type>
</vehicle>
<vehicle>
<name>Nissan</name>
<color>Red</color>
<type>Car</type>
</vehicle>
</vehicles>

所以在 Feed 1 中循环的标签是 car,而 Feed 2 是vehicle。

到目前为止,我提出的逻辑是循环连续出现的节点是否有办法检测到这一点。

4

1 回答 1

0

I am going to make a few assumptions here since I couldn't make much from the question.

  1. You want to parse XML in php and need php code
  2. You want to match the <car> tag in first xml file to <vehicle> tag in second xml file.

Based on the above assumption, here is the program for it


$xml1 = simplexml_load_string($xmlData1,null, LIBXML_NOERROR | LIBXML_NOWARNING); //$xmlData1 is the first xml 
$carsArr = array();
foreach ($xml1->cars->car as $car) {
    $carsArr[(string)$car->name] = array();
    $carsArr[(string)$car->name]= (string)$car->color; //create map of car name to color
}


$xml2 = simplexml_load_string($$xmlData2,null, LIBXML_NOERROR | LIBXML_NOWARNING); //$xmlData2 is the second xml
foreach($xml2->vehicle as $vehicle) {
    $name = (string)$vehicle->name;
    if(isset($carsArr[$name])) {
        echo "Name:".$name.",Color:".$carsArr[$name].",Type:".$vehicle->type."
"; } }

The output will be:

Name:Ford,Color:Blue,Type:Pickup
Name:Nissan,Color:Red,Type:Car

In this way, you can detect repeating nodes between two files.

于 2013-07-24T00:00:29.610 回答