0

Hi all i have an xml file e.g

<recipe>
    <id>abc</id>
    <name>abc</name>
    <instructions>
        <instruction>
            <id>abc</id>
            <text>abc</text>
        </instruction>
        <instruction>
            <id>abc2</id>
            <text>abc2<text>
        <instruction>
    <instructions>
<recipe>

on my php file i use

$url = "cafe.xml";
// get xml file contents
$xml = simplexml_load_file($url);

// loop begins
foreach($xml->recipe as $recipe)
{
code;
}

but it only retrieve the recipe id and name so how can i retrieve the instructions.

1
  • maybe in code, you have to access to $recipe->instructions or similar? Commented Nov 22, 2010 at 8:01

2 Answers 2

3

You should be able to do this:

foreach($xml->recipe as $recipe) {
    foreach($recipe->instructions->instruction as $instruction) {
        // e.g echo $instruction->text
    } 
}

If recipe is your root node, it should look like this:

foreach($xml->instructions->instruction as $instruction) {
    // e.g echo $instruction->text
} 

Have a look at other examples.

Sign up to request clarification or add additional context in comments.

Comments

3

Here's a function to convert valid XML to a PHP array:

/**
 * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on
 * all non-array data
 *
 * Notes:
 *  Root XML tags are stripped
 *  Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
 *  Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
 *
 * @param mixed $input
 * @param callback $callback
 * @param bool $_recurse used internally, do not pass any value
 * @return array|FALSE Returns false on all failure
 */
function xmlToArray( $input, $callback = NULL, $_recurse = FALSE )
{
    // Get input, loading an xml string with simplexml if its the top level of recursion
    $data = ( ( !$_recurse ) && is_string( $input ) ) ? simplexml_load_string( $input ) : $input;

    // Convert SimpleXMLElements to array
    if ( $data instanceof SimpleXMLElement ) {
        $data = (array) $data;
    }

    // Recurse into arrays
    if ( is_array( $data ) ) foreach ( $data as &$item ) {
        $item = xmlToArray( $item, $callback, TRUE );
    }

    // Run callback and return
    return ( !is_array( $data ) && is_callable( $callback ) ) ? call_user_func( $callback, $data ) : $data;
}

1 Comment

If it converts XML to an array, the function should probably be called xmlToArray or similar :-)

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.