0

I'm having some serious trouble with this. What I'm trying to do is 'extract' all the contents of a specific node in XML, and turn these into PHP variables, in order to use them later on.

Heres a small sample XML test data set I'm using.

<RECIPES>
<RECIPE>
<TI>Cinnamon Rolls</TI>
<IN>1/2 ea Sweet dough mixture</IN>
<IN>1/2 c Packed light brown sugar</IN>
<IN>1/2 c Pecans; chopped</IN>
<IN>1/2 c Dark seedless raisins</IN>
<IN>1 tsp Ground cinnamon</IN>
<IN>1/4 c Butter OR margarine; melted</IN>
<IN>Sugar Glaze (below opt)</IN>
<PR>Some Stuff.</PR>
</RECIPE>
<RECIPE>
<TI>SWEET BISCUITS</TI>
<IN>2 c Baking mix</IN>
<IN>2/3 c Milk</IN>
<IN>1/4 c Cinnamon Sugar</IN>
<IN>2 tb Butter</IN>
<PR>Some other stuff</PR>
</RECIPE>
<RECIPE>

(Theres actually about 900's of these) What I want to achieve is to extract the data from each node, and convert them to a variable; Below is what I hope to end up with.

$variable="Cinamon Rolls";
$variable2="Sweet Biscuits";

Is there a way to accomplish this? From what I've been researching i'm pretty sure it's something to do with SimpleXML. I've managed to output the contents individually, but just can't figure out how to then store them.

Problem is solved Thanks everyone for the help,

 $obj = simplexml_load_string($xml);

    foreach($obj->RECIPE as $r) {
        $variable = (string)$r->TI;
        echo $variable; }

Superb, thanks very much. Saved my ass.

1

2 Answers 2

1

Use SimpleXML:

$obj = simplexml_load_string($xml);

foreach($obj->RECIPE as $r)
{
    $variable = (string)$r->TI;
    echo $variable;
} 

Outputs

Cinamon Rolls
Sweet Biscuits

codepad Demo

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

2 Comments

Actually the assignmen into variables isn't really needed. Just load the string/file with simplexml_load_file() or simplexml_load_string() and then look at the object you get with var_dump(). Anyways. +1
@Jan yes, the assignment is not required, but OP asked to store it in $variable, but you are right, we could of course just echo (string)$r->TI; directly.
1

In an array?

$xml = simplexml_load_file($file_location);
$array = array();

foreach ($xml->RECIPE as $recipe){
    $array[] = $recipe->TI
}

Comments

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.