How to pass an xml to foreach without using a file?

Asked

Viewed 403 times

1

From the data returned by a query, I would like to generate an xml, but without saving it in file and go through the xml tags to handle the data in some way. I would like to know how to pass xml to foreach without having this xml file.

Suppose the generated xml is:

<disciplinas>
<disciplina id="1">
    <periodo>1</periodo>
    <nome>matematica</nome>
</disciplina>
<disciplina id="id_disciplina">
    <periodo>1</periodo>
    <nome>portugues</nome>
</disciplina>
<disciplina id="2">
    <periodo>1</periodo>
    <nome></nome>
</disciplina>
<disciplina id="3">
    <periodo>2</periodo>
    <nome>historia</nome>
</disciplina>
</disciplinas>

With xml, I want to check the data to generate a rowspan table where the "period" values repeat

tabela com rowspan

instead of a table without rowspan.

tabela sem rowspan

  • you want to print to xml on screen without generating file download?

  • But what’s the point of this? If you’re not going to store it in a file, at least you’ll echo the result to, who knows, be used with AJAX. However, that being the case, why do you want to create the XML, go through it and change some value and then maybe display it, if you can do the opposite, iterating the array returned from the query, handle what you need and only then mount the XML already ready?

  • @Louis Henry, you changed the question, but my answer still fits your case. However, I’m already wondering if you really want to turn this XML into an array or object to be able to foreach. That’s it ?

1 answer

1

Simple:

  1. query
  2. processes with the laço;
  3. generates string XML
  4. echo in the header and in the XML as body of the document

Example:

<?php

$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

Upshot:

<?xml version="1.0"?>
<root>
  <blub>bla</blub>
  <bar>foo</bar>
  <overflow>stack</overflow>
</root>

Consider $test_array as the result of processing in step 2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.