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>

1 Answer 1

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"); 
Sign up to request clarification or add additional context in comments.

2 Comments

There is no line it just says Fatal Error, also there is another error saying "Stack Trace: thrown in /path/ on line 4"
The error is possibly due to XML module not installed. Try this question to install XML module. stackoverflow.com/questions/31206186/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.