我有一个像这样的XML文件:
<GenResponse>
<Detail1></Detail1>
<Detail2></Detail>
<DataNodes>
<DataNode>
<NodeDetails1>
<node4>Parrot Musky Truck Moo</node4>
<node5>Tinker Singer Happy Fool</node5>
<node6>
<FurtherDetails>
<Node>Musky</Node>
<Node>Lorem Ipsum</Node>
</FurtherDetails>
</NodeDetails1>
<NodeDetails2>ID</NodeDetails2>
</DataNode>
<DataNode>
<NodeDetails1>
<node4>Sky Star Panet Shoe</node4>
<node5>Rusky Husky Musky Boo</node5>
</NodeDetails1>
<NodeDetails2>ID</NodeDetails2>
</DataNode>
</DataNodes>
</GenResponse>
我想知道如何将一个搜索字符串“Musky”注入PHP函数并返回<DataNode>...</DataNode>
&amp; <DataNode>...</DataNode>
回来了?
基本上我想在一个巨大的XML文件中搜索一个字符串,并返回包含该字符串的所有DataNode。
如果使用SimpleXML可以实现这一点,那就太棒了。否则任何其他解决方案也没问题。
编辑:注意“{Musus”“如何在<DataNode>
答案 0 :(得分:1)
使用
$xmlStr = file_get_contents('data/your_XML_File.xml');
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find nodes with text
$res = $xml->xpath("node2[contains(., 'Musky')]");
print_r($res);
//为了测试目的,只需在编辑器中复制粘贴代码,为了测试,我没有使用单独的xml文件。
<?php
//$xmlStr = file_get_contents('test.xml');
$xmlStr = '<node1>
<node2>
<node3>
<node4>Parrot Singer Truck Moo</node4>
<node5>Tinker Musky Happy Fool</node5>
</node3>
<node7>ID</node7>
</node2>
<node2>
<node3>
<node4>Sky Star Panet Shoe</node4>
<node5>Rusky Husky Musky Boo</node5>
</node3>
<node7>ID</node7>
</node2>
</node1>';
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find nodes with text
$res = $xml->xpath("node2[contains(., 'Musky')]");
echo "<pre>";
print_r($res);
?>
它提供了正确的输出,我试过
Array
(
[0] => SimpleXMLElement Object
(
[node3] => SimpleXMLElement Object
(
[node4] => Parrot Singer Truck Moo
[node5] => Tinker Musky Happy Fool
)
[node7] => ID
)
[1] => SimpleXMLElement Object
(
[node3] => SimpleXMLElement Object
(
[node4] => Sky Star Panet Shoe
[node5] => Rusky Husky Musky Boo
)
[node7] => ID
)
)
答案 1 :(得分:0)
使用此代码,您可以找到您的搜索词。我已将其设为function
,只需传递您的关键字即可获得结果,
function findWord($findVar)
{
$catalog = simplexml_load_file("xmlfile.xml");
$category = $catalog->node2;
$found = 0;
foreach($category as $c)
{
foreach($c->node3 as $node3)
{
$node4 = (string) ($node3->node4);
$node5 = (string) ($node3->node5);
if (stripos(strtolower($node4),strtolower($findVar)))
{
echo 'Found!!'.'<br/>';
$found++;
}
if (stripos(strtolower($node5),strtolower($findVar)))
{
echo 'Found!!'.'<br/>';
$found++;
}
}
if (stripos(strtolower((string)$c->node7),strtolower($findVar)))
{
echo 'Found!!'.'<br/>';
$found++;
}
}
if ($found == 0)
{
echo "No result";
}
}
$findVar = 'Musky';
findWord($findVar);