php get xml inner tag content

989

I need to perform an API that it's response is a XML. But the XML values are inside the XML tags.

For example

<example>
 <item productid = "1" productname = "xxx" cost = "5.3"/>
 <item productid = "2" productname = "yyy" cost = "4.0"/>
 <item productid = "3" productname = "zzz" cost = "1.75"/>
</example>

Can anyone tell me how can i, move between tags and get elemnt values For example:

example:
 item:
   productid -> 1,
   productname -> xxx,
   cost -> 5.3  
 item:
   productid -> 2,
   productname -> yyy,
   cost -> 4.0 
 item:
   productid -> 3,
   productname -> zzz,
   cost -> 1.75

Thanx

798

Answer

Solution:

XPath: http://php.net/manual/en/simplexmlelement.xpath.php

Not mandatory, you can just get all the children and loop through them, but XPath is more versatile in real world scenarios ( where you have multiple levels of XML nodes ) and is considerably more readable.

<?php
$xmlStr = <<<END
<example>
 <item productid = "1" productname = "xxx" cost = "5.3"/>
 <item productid = "2" productname = "yyy" cost = "4.0"/>
 <item productid = "3" productname = "zzz" cost = "1.75"/>
</example>
END;
$xml = new SimpleXMLElement($xmlStr); 

$items = $xml->xpath("//example/item");

$out = array();
foreach($items as $x) {
    $out [] = $x->attributes();
} 
542

Answer

Solution:

Or you could use DOMElement

$doc = new DOMDocument();
$doc->load('domexample.xml');
$elements = $doc->getElementsByTagName('item');

$x = 0;
foreach($elements as $element)
{
    $results[$x]['productid'] = $element->getAttribute('productid');
    $results[$x]['productname'] = $element->getAttribute('productname');
    $results[$x]['cost'] = $element->getAttribute('cost');
    $x++;
}
444

Answer

Solution:

<?php

$file = "filename.xml"; 
$example = simplexml_load_file($file) or die("Error: Can't Open File");

$prodidz = array();
$prodnamez = array();
$costz = array();

foreach ($example->children() as $item)
{
 $prodidz[] = $item->attributes()->productid;
 $prodnamez[] = $item->attributes()->productname;
 $costz[] = $item->attributes()->cost;
}

?>

People are also looking for solutions to the problem: php - getServiceLocator only works with LoginController

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.