0

I'm trying to display specific nodes from a .xml file with PHP depending on the variable

I would like to know if there is another way to make it work or to know what's wrong with my code.

I'm trying to only display <name> from the .xml file.

Here is my code that doesn't work:

function display_xml_nodes($xmlstr, $node) {
    $xmlstr = simplexml_load_file("$xmlstr") or die("Error: name not found");
    echo $xmlstr->foods->products->product->name . "\n";
}

display_xml_nodes("ex_04.xml", "name");

Here is the .xml

<food>
    <foods>
        <title>Products</title>
        <products>
            <product>
                <name>Chcolate Bar</name>
                <price>1</price>
            </product>
            <product>
                <name>Milk</name>
                <price>0.50</price>
            </product>
            <product>
                <name>Water</name>
                <price>0.50</price>
            </product>
            <product>
                <name>Donut</name>
                <price>1.50</price>
            </product>
        </products>
    </foods>
</food>
halfer
  • 19,824
  • 17
  • 99
  • 186
John Smith
  • 51
  • 5

1 Answers1

0

I think the problem is with this line.

$xmlstr = simplexml_load_file("$xmlstr") or die("Error: name not found");

You have given the variable name $xmlstr as the string to the function simplexml_load_file () not what's within that variable (the actual file name).

So change that line as follows,

$xmlstr = simplexml_load_file($xmlstr) or die("Error: name not found"); 
Nadun Kulatunge
  • 1,567
  • 2
  • 20
  • 28
  • There is no line it just says Fatal Error, also there is another error saying "Stack Trace: thrown in /path/ on line 4" – John Smith Apr 24 '18 at 14:25
  • 1
    The error is possibly due to XML module not installed. Try this question to install XML module. https://stackoverflow.com/questions/31206186/call-to-undefined-function-simplexml-load-string – Nadun Kulatunge Apr 24 '18 at 14:32