根据电子邮件匹配合并人员配置文件



我有一个现有的目录(带有xml数据源的php(,其中包含以下人员信息:

MainSource.xml

<people>
<person>
<id></id>
<last_name></last_name>
<first_name></first_name>
<email></email>
<phone></phone>
</person>
...
</people>

我需要从NewSource.xml向MainSource.xml添加一个新节点,匹配电子邮件地址,从包含以下人员信息的新数据源:

NewSource.xml

<people>
<person>
<email></email>
<website_url></website_url>
</person>
...
</people>

我尝试了很多变体,但我认为我的问题是正确地比较了这两份文件。从逻辑上讲,感觉我需要迭代,而不是foreach?还是两个前臂,每个来源一个?这是我思考的一个例子。请提供任何清晰或见解,以推动我朝着正确的方向前进。

<?php
$doc1 = new DOMDocument();
$doc1->load('MainSource.xml');
$doc2 = new DOMDocument();
$doc2->load('NewSource.xml');

foreach ($doc1->person as $person) {
if ($person->email === $doc2->person->email) {
$node = $doc1->createElement("website_url", $valueFromDoc2);
$newnode = $doc1->appendChild($node);
}
}
$merged = $doc1->saveXML();
file_put_contents('MergedSource.xml', $merged)
?>

正如@waterloomat所提到的,您需要使用xpath来实现这一点。

假设MainSource.xml看起来像这样:

<people>
<person>
<id>1</id>
<last_name>smith</last_name>
<first_name>john</first_name>
<email>js@example.com</email>
<phone>555-123-1234</phone>
</person>
<person>
<id>2</id>
<last_name>doe</last_name>
<first_name>jane</first_name>
<email>jd@anotherexample.com</email>
<phone>666-234-2345</phone>
</person>
</people>

CCD_ 2看起来像这样:

<people>
<person>
<email>js@example.com</email>
<website_url>js.example.com</website_url>
</person>
<person>
<email>jd@anotherexample.com</email>
<website_url>jd.anotherexample.com</website_url>
</person>
</people>

你可以试试这个:

$doc1->loadXML('MainSource.xml');    
$xpath1 = new DOMXPath($doc1);
# find each person's email address
$sources = $xpath1->query('//person//email');
$doc2->loadXML('NewSource.xml');
$xpath2 = new DOMXPath($doc2);
foreach ($sources as $source) {
#for each email address, get the parent and use that as the destination
#of the new web address element
$destination = $xpath1->query('..',$source);
#in the other doc, search for each person whose email address matches
#that of the first doc and get the relevant web address
$exp2 = "//person[email[text()='{$source->nodeValue}']]//website_url";
$target = $xpath2->query($exp2);
#import the result of the search as a node into the first doc
$node = $doc1->importNode($target[0], true);
#finally, append the imported node in the right location of the first doc
$destination[0]->appendChild($node);
};
echo $doc1->saveXml();

输出:

<people>
<person>
<id>1</id>
<last_name>smith</last_name>
<first_name>john</first_name>
<email>js@example.com</email>
<phone>555-123-1234</phone>
<website_url>js.example.com</website_url></person>
<person>
<id>2</id>
<last_name>doe</last_name>
<first_name>jane</first_name>
<email>jd@anotherexample.com</email>
<phone>666-234-2345</phone>
<website_url>jd.anotherexample.com</website_url></person>
</people>

最新更新