Reputation: 1093
My XML input is like this:
<Configuaration>
<Allowances>
<payhead>
<code>123</code>
<name_en>Basic</name_en>
<source>anything</source>
</payhead>
</Allowances>
<Deductions>
<payhead>
<code>444</code>
<name_en>House Rent</name_en>
<source>anything</source>
</payhead>
</Deductions>
</Configuaration>
What I want is like, in my php function I will give 2 parameters. 1st one is the input xml and 2nd one is the searchTag (all child nodes under this tag should return).
my php function:
<?php
class myXMLUtil
{
public static function getValue($inputXML, $searchTag)
{
$dom = new DOMDocument;
$dom->loadXML($inputXML);
$childs = $dom->getElementsByTagName($searchTag);
foreach ($childs as $child) {
echo '<'.$child->nodeName.'>'.$child->nodeValue.'</'.$child->nodeName.'>'.PHP_EOL;
}
}
}
?>
so if i put the_xml_string and 'payhead' as the function parameter then it should return
<payhead>
<code>123</code>
<name_en>Basic</name_en>
<source>anything</source>
</payhead>
<payhead>
<code>123</code>
<name_en>Basic</name_en>
<source>anything</source>
</payhead>
but instead i get
<payhead>123Basicanything</payhead>
<payhead>444House Rentanything</payhead>
I dont understand it. Can anybody help? If there is something wrong in my code then how can I achieve it? TIA.
Upvotes: 2
Views: 53
Reputation: 5534
It looks like you need this function:
class myXMLUtil
{
public static function getValue($inputXML, $searchTag)
{
$dom = new DOMDocument;
$dom->loadXML($inputXML);
$foundElements = $dom->getElementsByTagName($searchTag);
foreach ($foundElements as $foundElement) {
echo $foundElement->ownerDocument->saveXML($foundElement);
}
}
}
You can run locally this code:
<?php
$xml = <<<EOF
<Configuaration>
<Allowances>
<payhead>
<code>123</code>
<name_en>Basic</name_en>
<source>anything</source>
</payhead>
</Allowances>
<Deductions>
<payhead>
<code>444</code>
<name_en>House Rent</name_en>
<source>anything</source>
</payhead>
</Deductions>
</Configuaration>
EOF;
class myXMLUtil
{
public static function getValue($inputXML, $searchTag)
{
$dom = new DOMDocument;
$dom->loadXML($inputXML);
$foundElements = $dom->getElementsByTagName($searchTag);
foreach ($foundElements as $foundElement) {
echo $foundElement->ownerDocument->saveXML($foundElement);
}
}
}
myXMLUtil::getValue($xml, 'payhead');
?>
And it will return
<payhead>
<code>123</code>
<name_en>Basic</name_en>
<source>anything</source>
</payhead><payhead>
<code>444</code>
<name_en>House Rent</name_en>
<source>anything</source>
</payhead>
Upvotes: 2