Data structure to save nested XML based data - php

I obtain this type of response via curl:
<ArrayOfServerFile>
<ServerFile>
...
<FileType>Folder</FileType>
<Identifier>x123</Identifier>
<Name>Client Templates</Name>
...
</ServerFile>
<ServerFile>
...
<FileType>XpressDox Template</FileType>
<Identifier>y456</Identifier>
<Name>contact-information.xdtpl</Name>
...
</ServerFile>
...
</ArrayOfServerFile>
I want to save this info in a tree-like data structure.
I have tried something like this:
// Pseudo-code:
function run_procedure()
{
get XML data via curl
if FileType == 'Folder'
save name and other useful data into $tree_like_data_structure
run_procedure() // recursive call
else if FileType == 'XpressDox Template'
save name and other useful data into $tree_like_data_structure
}
var_dump($tree_like_data_structure);
The idea is to represent saved data like this:
[0][0] -> data
[1][0] -> data
[1][1] -> data
[1][2] -> [2][0] -> data
[2][1] -> data
[1][3] -> data
I am pretty sure that this is not so hard to accomplish but I have lost a lot of time without success. Any tip is very welcome. Thanks.-
EDIT 1
My main concern is how obtain [depth][element] indexes and how level data (type, name, content, etc).
EDIT 2
Basically this is a recursive programming problem. Maybe it can be done via while statements more easily than with a recursive function?

Try using SimpleXML with the DOM to create your array.
$dom = new DOMDocument;
$dom->loadXML('
<ArrayOfServerFile>
<ServerFile>
<FileType>Folder</FileType>
<Identifier>x123</Identifier>
<Name>Client Templates</Name>
</ServerFile>
</ArrayOfServerFile>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}
$s = simplexml_import_dom($dom);
echo $s->ServerFile[0]->FileType;

Related

PHP -> Curl -> Soap Response (Get data from xml tags)

I have a Curl response with Soap XML data.
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/><SOAP-ENV:Body><ns2:GetAccountMovementsResponseIo xmlns:ns2="http://www.mygemini.com/schemas/mygemini">
<ns2:result>
<ns2:pager>
<ns2:pageIndex>0</ns2:pageIndex>
<ns2:pageSize>700</ns2:pageSize>
</ns2:pager>
<ns2:totalCount>3</ns2:totalCount>
</ns2:result>
<ns2:accountMovement>
<ns2:movementId>002147575330.2</ns2:movementId>
<ns2:paymentId>95694091</ns2:paymentId>
<ns2:externalPaymentId>2147575330</ns2:externalPaymentId>
<ns2:debitCredit>1</ns2:debitCredit>
<ns2:valueDate>2018-12-13T00:00:00+04:00</ns2:valueDate>
<ns2:description>გადარიცხვა პირად ანგარიშზე</ns2:description>
<ns2:amount>
<ns2:amount>10000</ns2:amount>
<ns2:currency>GEL</ns2:currency>
</ns2:amount>
<ns2:accountNumber>GE44TB7142536020100005</ns2:accountNumber>
<ns2:accountName>კლიენტი:1425</ns2:accountName>
<ns2:additionalInformation>კლიენტი:1425, 123456786, TBCBGE22, GE17TB7142536020100006</ns2:additionalInformation>
<ns2:documentDate>2018-12-13T00:00:00+04:00</ns2:documentDate>
<ns2:documentNumber>1544698824</ns2:documentNumber>
<ns2:partnerAccountNumber>GE17TB7142536020100006</ns2:partnerAccountNumber>
<ns2:partnerName>კლიენტი:1425, 123456786</ns2:partnerName>
<ns2:partnerTaxCode>123456786</ns2:partnerTaxCode>
<ns2:partnerBankCode>TBCBGE22</ns2:partnerBankCode>
<ns2:partnerBank>სს თიბისი ბანკი</ns2:partnerBank>
<ns2:taxpayerCode>123456786</ns2:taxpayerCode>
<ns2:taxpayerName>კლიენტი:1425, 123456786</ns2:taxpayerName>
<ns2:operationCode>GII</ns2:operationCode>
<ns2:partnerDocumentType>0</ns2:partnerDocumentType>
<ns2:statusCode>3</ns2:statusCode>
<ns2:transactionType>1</ns2:transactionType>
</ns2:accountMovement>
<ns2:accountMovement>
<ns2:movementId>002147575330.1</ns2:movementId>
<ns2:paymentId>95694091</ns2:paymentId>
<ns2:externalPaymentId>2147575330</ns2:externalPaymentId>
<ns2:debitCredit>0</ns2:debitCredit>
<ns2:valueDate>2018-12-13T00:00:00+04:00</ns2:valueDate>
<ns2:description>გადარიცხვა პირად ანგარიშზე</ns2:description>
<ns2:amount>
<ns2:amount>10000</ns2:amount>
<ns2:currency>GEL</ns2:currency>
</ns2:amount>
<ns2:accountNumber>GE17TB7142536020100006</ns2:accountNumber>
<ns2:accountName>კლიენტი:1425, 123456786</ns2:accountName>
<ns2:additionalInformation>კლიენტი:1425, TBCBGE22, GE44TB7142536020100005</ns2:additionalInformation>
<ns2:documentDate>2018-12-13T00:00:00+04:00</ns2:documentDate>
<ns2:documentNumber>1544698824</ns2:documentNumber>
<ns2:partnerAccountNumber>GE44TB7142536020100005</ns2:partnerAccountNumber>
<ns2:partnerName>კლიენტი:1425</ns2:partnerName>
<ns2:partnerTaxCode>123456786</ns2:partnerTaxCode>
<ns2:partnerBankCode>TBCBGE22</ns2:partnerBankCode>
<ns2:partnerBank>სს თიბისი ბანკი</ns2:partnerBank>
<ns2:taxpayerCode>123456786</ns2:taxpayerCode>
<ns2:taxpayerName>კლიენტი:1425, 123456786</ns2:taxpayerName>
<ns2:operationCode>GII</ns2:operationCode>
<ns2:partnerDocumentType>0</ns2:partnerDocumentType>
<ns2:statusCode>3</ns2:statusCode>
<ns2:transactionType>1</ns2:transactionType></ns2:accountMovement>
<ns2:accountMovement><ns2:movementId>002147575329.2</ns2:movementId>
<ns2:externalPaymentId>2147575329</ns2:externalPaymentId>
<ns2:debitCredit>1</ns2:debitCredit>
<ns2:valueDate>2018-12-13T00:00:00+04:00</ns2:valueDate>
<ns2:description>ანგარიშზე თანხის შეტანა</ns2:description><ns2:amount>
<ns2:amount>100000</ns2:amount><ns2:currency>GEL</ns2:currency></ns2:amount>
<ns2:accountNumber>GE17TB7142536020100006</ns2:accountNumber>
<ns2:accountName>კლიენტი:1425</ns2:accountName>
<ns2:additionalInformation>სახელი:3928462 გვარი3928462</ns2:additionalInformation>
<ns2:documentDate>2018-12-13T00:00:00+04:00</ns2:documentDate>
<ns2:documentNumber>63946130</ns2:documentNumber>
<ns2:partnerAccountNumber>GE78TB0000000000060000</ns2:partnerAccountNumber>
<ns2:partnerName>სახელი:3928462 გვარი3928462</ns2:partnerName>
<ns2:partnerTaxCode>00000000000</ns2:partnerTaxCode>
<ns2:partnerBankCode>TBCBGE22</ns2:partnerBankCode><ns2:partnerBank>ს.ს. „თიბისი ბანკი”</ns2:partnerBank>
<ns2:operationCode>01</ns2:operationCode>
<ns2:partnerPersonalNumber>00000000000</ns2:partnerPersonalNumber>
<ns2:partnerDocumentType>6</ns2:partnerDocumentType>
<ns2:partnerDocumentNumber>DC102086</ns2:partnerDocumentNumber>
<ns2:statusCode>3</ns2:statusCode>
<ns2:transactionType>20</ns2:transactionType>
</ns2:accountMovement>
</ns2:GetAccountMovementsResponseIo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I would like to get data inside tags one by one
<ns2:paymentId>, <ns2:externalPaymentId>, <ns2:debitCredit> etc.
Kindly note that this is dummy data of a bank statement, and in real life responses have multiple tags with the same name per each transaction. For example, if there are 11 transactions, there will be 11 <ns2:paymentId> tags and I need to get data one by one.
Using SimpleXML you can read the code and the data much easier. The only thing is that you need to respect the namespaces. So first register the ns2 namespace so that you can then you can fetch the <ns2:accountMovement> elements. The loop over these, but to access the child elements in the namespace, use children("http://www.mygemini.com/schemas/mygemini") to get them into the $data variable, then each access is via this (i.e. $data->paymentId)...
$xml = simplexml_load_string($xmlContent);
$xml->registerXPathNamespace("ns2", "http://www.mygemini.com/schemas/mygemini");
$movements = $xml->xpath("//ns2:GetAccountMovementsResponseIo/ns2:accountMovement");
foreach ( $movements as $accMove ) {
$data = $accMove->children("http://www.mygemini.com/schemas/mygemini");
echo "paymentId ->".$data->paymentId.PHP_EOL;
echo "externalPaymentId ->".$data->externalPaymentId.PHP_EOL;
echo "debitCredit ->".$data->debitCredit.PHP_EOL;
}

Extracting a precise value from a Json array with PHP (like a MySQL db)

another (probably) easy question for you.
As I wrote many times, I'm not a programmer but thanks to you I was able to build an interesting site for my uses.
So again thx.
This is my new problem:
I have a site that recover json data from a file and store it locally once a day (this is the code - I post it so it can be useful to anyone):
// START
findList();
function findList() {
$serverName = strtolower($_POST["Server"]); // GET SERVER FROM FORM POST
$localCoutryList = ("json/$serverName/countries.json"); // LOCAL LOCATIONS OF FILE
$urlCountryList = strtolower("url.from.where.I.get.Json.file.$serverName/countries.json"); // ONLINE LOCATION OF FILE
if (file_exists($localCoutryList)) { // FILE EXIST
$fileLastMod = date("Y/m/d",filemtime($localCoutryList)); // IF FILE LAST MOD = FILE DATE TIME
$now = date('Y/m/d', time()); // NOW
if ($now != $fileLastMod) { // IF NOW != FILE LAST MOD (date)
createList($serverName,$localCoutryList,$urlCountryList); // GO AND CREATE FILE
} else { // IF NOW = FILE LAST MOD (date)
jsonList($serverName,$localCoutryList,$urlCountryList); // CALL JSON DATA FROM FILE
}} else { // FILE DOESN'T EXIST
createList($serverName,$localCoutryList,$urlCountryList); // CALL CREATE FILE
}};
function createList($serverName,$localCoutryList,$urlCountryList) {
file_put_contents($localCountryList, file_get_contents($urlCountryList)); // CREATE FILE
jsonList($serverName); // CALL JSON DATA FROM FILE
};
function jsonList($serverName,$localCoutryList,$urlCountryList) { // JSON DATA FROM FILE
$jsonLoopCountry = file_get_contents($localCoutryList); // GET CONTENT OF THE LOCAL FILE
$outLoopCountry = json_decode($jsonLoopCountry, true); // DECODE JSON FILE
$countryList = $outLoopCountry['country']; // ACCESS TO JSON OBJECT
foreach ($countryList as $dataCountry) { // FOR EACH "COUNTRY" IN JSON DECODED OBJECT
// SET VARS FOR ALL THE COUNTRIES
$iscountryID = ($dataCountry['id']); // TEST
$countryCurrency = ($dataCountry['curr']); // TEST
$countryName = ($dataCountry['name']);} // TEST
echo "<br>total country list: ".count($countryList); // THIS RETURN TOTAL ELEMENTS IN THE ARRAY
[...]
The kind of Json data I'm working with is structured as it follows:
{"country":[{"id":130,"curr":"AFN","name":"Afghanistan"},{"id":55,"curr":"ALL","name":"Albania"},{"id":64,"curr":"DZD","name":"Algeria"},{"id":65,"curr":"AOA","name":"Angola"},{"id":24,"curr":"ARS","name":"Argentina"}...
So I can say that
$outLoopCountry = json_decode($jsonLoopCountry, true); // DECODE JSON FILE
creates the JSON ARRAY right? (Because JSON array starts with {"something":[{"..."...)
if it was [{"a":"answer","b":"answer",...} ... it would have a been a JSON Object right?
So to access to the array I uses
$countryList = $outLoopCountry['country']; // ACCESS TO JSON OBJECT
right?
So I understood that arrays are a fast useful ways to store relational data and access to it right?
So the question is how to make a precise search inside the array, so to make it works like a Query MySQLi, like "SEARCH INSIDE ARRAY WHERE id == 7" and have as a result "== ITALY" (ex.).
The way exist for sure, but with whole exmples I found on the net, I was able to fix one to make it works.
Thx again.
Alberto

PHP: Read existing xml file and write new content

I have a .xsd-file and of course I can create a .xml-file from it. So basically I have a blank .xml-file (with no data/text)
With PHP I want to read the blank .xml-file, interate the nodes and fill them depending on the tag with data from the database.
There seem to be many options: XMLReader, XMLWriter, DOMDocument, SimpleXML
I don't know where to start. What would be the easies/leanest way?
More Information:
Here you kann find the .xsd-file...
The following .xml-file I created:
<?xml version="1.0" encoding="utf-8"?><Patienten>
<InfoXML>
<DatumXML></DatumXML>
<NameTudokusys></NameTudokusys>
<VersionTudokusys></VersionTudokusys>
</InfoXML>
<Patient>
<Stammdaten>
<PatientID></PatientID>
<GeburtsJahr></GeburtsJahr>
<GeburtsMonat></GeburtsMonat>
<GeburtsTag></GeburtsTag>
<Geschlecht></Geschlecht>
<EinwilligungTumordoku></EinwilligungTumordoku>
<EinwilligungExterneStelle></EinwilligungExterneStelle>
</Stammdaten>
<Fall>
<Anamnese>
<RelevanteKrebsvorerkrankungen></RelevanteKrebsvorerkrankungen>
<JahrRelevanteKrebsvorerkrankungen></JahrRelevanteKrebsvorerkrankungen>
<NichtRelevanteKrebsvorerkrankungen></NichtRelevanteKrebsvorerkrankungen>
<JahrNichtRelevanteKrebsvorerkrankungen></JahrNichtRelevanteKrebsvorerkrankungen>
<DKGPatientenfragebogen></DKGPatientenfragebogen>
<PositiveFamilienanamnese></PositiveFamilienanamnese>
</Anamnese>
<Grundgesamtheiten></Grundgesamtheiten>
<Fallinfos>
<Zentrumsfall></Zentrumsfall>
<Organ></Organ>
<RegNr></RegNr>
<HauptNebenStandort></HauptNebenStandort>
<FallNummer></FallNummer>
<EingabeFalldaten></EingabeFalldaten>
</Fallinfos>
<Diagnose>
<DatumErstdiagnosePrimaertumor></DatumErstdiagnosePrimaertumor>
<DatumHistologischeSicherung></DatumHistologischeSicherung>
<ICDOHistologieDiagnose></ICDOHistologieDiagnose>
<Tumorauspraegung></Tumorauspraegung>
<ICDOLokalisation></ICDOLokalisation>
<KolonRektum></KolonRektum>
<TumorlokalisationRektum></TumorlokalisationRektum>
<praeT></praeT>
<praeN></praeN>
<praeM></praeM>
<UICCStadium></UICCStadium>
<SynchroneBehandlungKolorektalerPrimaertumoren></SynchroneBehandlungKolorektalerPrimaertumoren>
<MRTBecken></MRTBecken>
<CTBecken></CTBecken>
<AbstandFaszie></AbstandFaszie>
</Diagnose>
<PraetherapeutischeTumorkonferenz>
<VorstellungPraetherapeutischeTumorkonferenz></VorstellungPraetherapeutischeTumorkonferenz>
<EmpfehlungPraetherapeutischeTumorkonferenz></EmpfehlungPraetherapeutischeTumorkonferenz>
</PraetherapeutischeTumorkonferenz>
<EndoskopischePrimaertherapie>
<DatumTherapeutischeKoloskopie></DatumTherapeutischeKoloskopie>
<OPSCodeEndoskopischePrimaertherapie></OPSCodeEndoskopischePrimaertherapie>
</EndoskopischePrimaertherapie>
<ChirurgischePrimaertherapie>
<ASAKlassifikation></ASAKlassifikation>
<DatumOperativeTumorentfernung></DatumOperativeTumorentfernung>
<OPSCodesChirurgischePrimaertherapie></OPSCodesChirurgischePrimaertherapie>
<NotfallOderElektiveingriff></NotfallOderElektiveingriff>
<Erstoperateur></Erstoperateur>
<Zweitoperateur></Zweitoperateur>
<AnastomoseDurchgefuehrt></AnastomoseDurchgefuehrt>
<TMEDurchgefuehrt></TMEDurchgefuehrt>
<PostoperativeWundinfektion></PostoperativeWundinfektion>
<DatumPostoperativeWundinfektion></DatumPostoperativeWundinfektion>
<AufgetretenAnastomoseninsuffizienz></AufgetretenAnastomoseninsuffizienz>
<AnastomoseninsuffizienzInterventionspflichtig></AnastomoseninsuffizienzInterventionspflichtig>
<DatumInterventionspflichtigeAnastomoseninsuffizienz></DatumInterventionspflichtigeAnastomoseninsuffizienz>
<Revisionseingriff></Revisionseingriff>
<DatumRevisionseingriff></DatumRevisionseingriff>
<OPmitStoma></OPmitStoma>
<Stomaangezeichnet></Stomaangezeichnet>
</ChirurgischePrimaertherapie>
<PostoperativeHistologieStaging>
<pT></pT>
<pN></pN>
<postM></postM>
<Grading></Grading>
<ICDOHistologiePostoperative></ICDOHistologiePostoperative>
<PSRLokalNachAllenOPs></PSRLokalNachAllenOPs>
<PSRGesamtNachPrimaertherapie></PSRGesamtNachPrimaertherapie>
<GueteDerMesorektumresektion></GueteDerMesorektumresektion>
<AnzahlDerUntersuchtenLymphknoten></AnzahlDerUntersuchtenLymphknoten>
<AbstandAboralerTumorrand></AbstandAboralerTumorrand>
<AbstandZirkumferentiellerTumorrand></AbstandZirkumferentiellerTumorrand>
</PostoperativeHistologieStaging>
<PostoperativeTumorkonferenz>
<VorstellungPostoperativeTumorkonferenz></VorstellungPostoperativeTumorkonferenz>
<EmpfehlungPostoperativeTumorkonferenz></EmpfehlungPostoperativeTumorkonferenz>
</PostoperativeTumorkonferenz>
<Lebermetastasen>
<LebermetastasenVorhanden></LebermetastasenVorhanden>
<LebermetastasenAusschliesslich></LebermetastasenAusschliesslich>
<PrimaereLebermetastasenresektion></PrimaereLebermetastasenresektion>
<BedingungenSenkundaereLebermetastasenresektion></BedingungenSenkundaereLebermetastasenresektion>
<SekundaereLebermetastasenresektion></SekundaereLebermetastasenresektion>
</Lebermetastasen>
<PraeoperativeStrahlentherapie>
<EmpfehlungPraeoperativeStrahlentherapie></EmpfehlungPraeoperativeStrahlentherapie>
<DatumEmpfehlungPraeoperativeStrahlentherapie></DatumEmpfehlungPraeoperativeStrahlentherapie>
<TherapiezeitpunktPraeoperativeStrahlentherapie></TherapiezeitpunktPraeoperativeStrahlentherapie>
<TherapieintentionPraeoperativeStrahlentherapie></TherapieintentionPraeoperativeStrahlentherapie>
<GruendeFuerNichtdurchfuehrungPraeoperativeStrahlentherapie></GruendeFuerNichtdurchfuehrungPraeoperativeStrahlentherapie>
<DatumBeginnPraeoperativeStrahlentherapie></DatumBeginnPraeoperativeStrahlentherapie>
<DatumEndePraeoperativeStrahlentherapie></DatumEndePraeoperativeStrahlentherapie>
<GrundDerBeendigungDerPraeoperativeStrahlentherapie></GrundDerBeendigungDerPraeoperativeStrahlentherapie>
</PraeoperativeStrahlentherapie>
<PostoperativeStrahlentherapie>
<EmpfehlungPostoperativeStrahlentherapie></EmpfehlungPostoperativeStrahlentherapie>
<DatumEmpfehlungPostoperativeStrahlentherapie></DatumEmpfehlungPostoperativeStrahlentherapie>
<TherapiezeitpunktPostoperativeStrahlentherapie></TherapiezeitpunktPostoperativeStrahlentherapie>
<TherapieintentionPostoperativeStrahlentherapie></TherapieintentionPostoperativeStrahlentherapie>
<GruendeFuerNichtdurchfuehrungPostoperativeStrahlentherapie></GruendeFuerNichtdurchfuehrungPostoperativeStrahlentherapie>
<DatumBeginnPostoperativeStrahlentherapie></DatumBeginnPostoperativeStrahlentherapie>
<DatumEndePostoperativeStrahlentherapie></DatumEndePostoperativeStrahlentherapie>
<GrundDerBeendigungDerPostoperativeStrahlentherapie></GrundDerBeendigungDerPostoperativeStrahlentherapie>
</PostoperativeStrahlentherapie>
<PraeoperativeChemotherapie>
<EmpfehlungPraeoperativeChemotherapie></EmpfehlungPraeoperativeChemotherapie>
<DatumEmpfehlungPraeoperativeChemotherapie></DatumEmpfehlungPraeoperativeChemotherapie>
<TherapiezeitpunktPraeoperativeChemotherapie></TherapiezeitpunktPraeoperativeChemotherapie>
<TherapieintentionPraeoperativeChemotherapie></TherapieintentionPraeoperativeChemotherapie>
<GruendeFuerNichtdurchfuehrungPraeoperativeChemotherapie></GruendeFuerNichtdurchfuehrungPraeoperativeChemotherapie>
<DatumBeginnPraeoperativeChemotherapie></DatumBeginnPraeoperativeChemotherapie>
<DatumEndePraeoperativeChemotherapie></DatumEndePraeoperativeChemotherapie>
<GrundDerBeendigungDerPraeoperativeChemotherapie></GrundDerBeendigungDerPraeoperativeChemotherapie>
</PraeoperativeChemotherapie>
<PostoperativeChemotherapie>
<EmpfehlungPostoperativeChemotherapie></EmpfehlungPostoperativeChemotherapie>
<DatumEmpfehlungPostoperativeChemotherapie></DatumEmpfehlungPostoperativeChemotherapie>
<TherapiezeitpunktPostoperativeChemotherapie></TherapiezeitpunktPostoperativeChemotherapie>
<TherapieintentionPostoperativeChemotherapie></TherapieintentionPostoperativeChemotherapie>
<GruendeFuerNichtdurchfuehrungPostoperativeChemotherapie></GruendeFuerNichtdurchfuehrungPostoperativeChemotherapie>
<DatumBeginnPostoperativeChemotherapie></DatumBeginnPostoperativeChemotherapie>
<DatumEndePostoperativeChemotherapie></DatumEndePostoperativeChemotherapie>
<GrundDerBeendigungDerPostoperativeChemotherapie></GrundDerBeendigungDerPostoperativeChemotherapie>
</PostoperativeChemotherapie>
<BestSupportiveCare></BestSupportiveCare>
<Prozess>
<DatumStudie></DatumStudie>
<Studientyp></Studientyp>
<PsychoonkologischeBetreuung></PsychoonkologischeBetreuung>
<BeratungSozialdienst></BeratungSozialdienst>
<GenetischeBeratungEmpfohlen></GenetischeBeratungEmpfohlen>
<GenetischeBeratungErhalten></GenetischeBeratungErhalten>
<ImmunhistochemischeUntersuchungAufMSI></ImmunhistochemischeUntersuchungAufMSI>
</Prozess>
<FollowUp>
<DatumFollowUp></DatumFollowUp>
<LokoregionaeresRezidiv></LokoregionaeresRezidiv>
<LymphknotenRezidiv></LymphknotenRezidiv>
<Fernmetastasen></Fernmetastasen>
<Zweittumor></Zweittumor>
<Verstorben></Verstorben>
<QuelleFollowUp></QuelleFollowUp>
</FollowUp>
</Fall>
</Patient>
First, I have to navigate to certain nodes (for example "DatumXML") and enter a value.
Second, I have to iterate all subnodes of certain nodes (for example Stammdaten) and enter values.
I think the SimpleXMLIterator is going to be your best bet. You didn't quite explain the structure of your XML, but you should be able to do something like:
$iterator = new SimpleXMLIterator($xml);
for ($iterator->rewind(); $iterator->valid(); $iterator->next()) {
$node = $iterator->key();
// Get data from database based on node name
$iterator->{$node} = $data;
}
$finished_xml = $iterator->asXML();
If you're structure is more complex, you should be able to adapt this to what you need. Just remember that a SimpleXMLIterator is a SimpleXMLElement and you can use the same methods and techniques.

Populate Flex ComboBox from XML from PHP

I'm having trouble populating a combobox from an XML response. Here is the XML that I am receiving:
<distros>
<entry>
<distro>CentOS</distro>
<distro>Debian</distro>
<distro>Other</distro>
<distro>Sabayon</distro>
<distro>Ubuntu</distro>
<distro>VMware</distro>
<distro>Windows</distro>
</entry>
</distros>
So probably the most basic form of XML ever!
and here is the flex code:
private function getDistros():void
{
httpReq = new HTTPService;
httpReq.url = 'http://myserver/xml.php';
httpReq.resultFormat = 'e4x';
httpReq.method = 'GET';
httpReq.addEventListener(ResultEvent.RESULT, popDistros);
httpReq.send( null );
}
private function popDistros(event:ResultEvent):void
{
if(event.result != "")
{
// Set the data to the XMLListCollection for lookup
myXmlCollection= new XMLListCollection(event.result.entry);
// Bind the ListCollection to the comboBox
Alert.show(myXmlCollection.toString());
distroCombo.dataProvider = myXmlCollection.toString();
}
}
and the MXML:
<mx:ControlBar x="139" y="10" width="266" height="358" verticalAlign="top" horizontalAlign="left" direction="vertical">
<mx:ComboBox id="distroCombo" labelField="distro"></mx:ComboBox>
<mx:ComboBox id="imageCombo"></mx:ComboBox>
<mx:Button label="Download"/>
</mx:ControlBar>
The XML comes back fine in the Alert but the comboBox won't populate and I have tried this so many different ways now, anyone got any suggestions? Have I just been staring at it far too long?
if the result (event.result) is XML, then It should wotk like this: (it differs with .distro in the end compared to yours)
myXmlCollection = new XMLListCollection(event.result.entry.distro);
...this should create valid data in myXmlCollection
But then also this row is wrong:
distroCombo.dataProvider = myXmlCollection.toString();
it creates just one item in dataProvider of type string, (Just BTW: if you would have used spark combobox, you would have get compile error at this row).
just use this instead:
distroCombo.dataProvider = myXmlCollection;
And also note, that you can see correct result in the Alert, but it does not say if the data are of correct type, coz Alert evertyhing converts to string :)

Code for communcation between PHP and AS2?

I have a Flash developer I'm working with. This person is building a tool in AS2 that will provide an interface that will send voting data (firstname, lastname, email address, votes (there are 100 items in categories and users will be able to choose some subset to declare "best").
All fair enough, Flash dev will POST data to a PHP app I will develop, and I will store the data in MySQL. This Flash dev has not done a great deal of work with databases or web apps.
I want to return data back to the Flash application. I want to be able to return "email address invalid" or "problem connecting to database" or "vote information accepted" messages. My instinct is to want to send back JSON or XML data. But I'm wondering if there are tools in AS2 to easily consume such responses.
I would like to see some "Hello World" type examples of AS2 code that consumes JSON or XML data so I can get the Flash app and the PHP app interacting well. My understanding is AMF is not on the table because it's AS2, but I'm open to what will work on both ends given the constraint of it being AS2.
Below should give you an example.
XML:
<alldots>
<dotname id="bigDot" color="0xff0000" url="http://www.fletchermartin.com/" photos="8" />
<dotname id="otherDot" color="0x000066" url="http://www.ajc.com/" photos="8" />
<dotname id="thirdDot" color="0xCC0099" url="http://www.tiffanybbrown.com/" photos="0" />
</alldots>
AS2 Code
var dots:XML = new XML();
dots.load('bigdot.xml');
dots.onLoad = function(success:Boolean){
if(success){
if(dots.status == 0){
var dotsToXMLString:String = new String(); // initializes a new string variable
dotsToXMLString = dots.toString(); // converts dots XML object to a string and stores it in dotsToXMLString.
var dotsXML:XML = new XML(dotsToXMLString);// creates new XML object with the string contents from above.
dotsXML.parseXML(dotsToXMLString); // parses the string from above.
var dotsNodes:Object = dotsXML.firstChild; // Saves the firstChild (in this case, the outermost element) as an object
var dotsNodesChildren:Object = dotsNodes.childNodes; // Saves the childNodes of firstChild as an object
for(i=0;i<dotsNodesChildren.length;i++){
var newObj:Object = dotsNodes.childNodes[i].attributes.id; // creates a new object out of the child node's id.
var newObjColor:Color = new Color(newObj); // creates a new color object with newObj as its target
var theColor:Number = dotsNodes.childNodes[i].attributes.color; //retrieves the hex code value (number) of the attribute color
newObjColor.setRGB(theColor); // sets the RGB value of newObjColor.
}
} else {
trace("Problem parsing XML.");
}
} else{
trace("Could not load XML");
}
}

Categories