开发者

parse nested xml into php

开发者 https://www.devze.com 2023-01-26 20:28 出处:网络
Hi all i have an xml file e.g <recipe> <id>abc</id> <name>abc</name> <instructions>

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>
    开发者_如何学JAVA<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.


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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消