logo
down
shadow

Parsing XML document with PHP using 'foreach' loop


Parsing XML document with PHP using 'foreach' loop

By : user2953484
Date : November 21 2020, 01:01 AM
should help you out You write that you've got problems to debug your issues traversing an XML document with SimpleXML.
The first puzzle you come over is that your foreach does only iterate once:
code :
foreach ($xml->alliances as $alliances) {
echo substr($xml->alliances->asXML(), 0, 256), "\n";

<alliances>
    <alliance>
    <alliance id="1">Harmless?</alliance>  
    <foundedbyplayerid id="10"/><alliancecapitaltownid id="14646"/>
    <allianceticker>H?</allianceticker>  
    <foundeddatetime>2010-02-25T14:18:07.867</foundeddatetime>  
    <alliancecapitallastmoved>2012-01-19T17:42
 ^^^^^^^^^
foreach ($xml->alliances->alliance as $alliances) {
 foreach ($xml->alliances->alliance as $alliance) {
$alliances = $xml->alliances->alliance;
foreach ($alliances as $alliance) {
$alliances = $xml->alliances->alliance;
foreach ($alliances as $alliance) {

    // Alliance info
    $alliance_id   = trim($alliance->alliance->alliance['id']);
    $alliance_name = trim($alliance->alliance->alliance);

    // Diplomacy info
    $proposed_by_alliance_id = trim($alliance->alliance->relationships->relationship->proposedbyalliance['id']);
    $accepted_by_alliance_id = trim($alliance->alliance->relationships->relationship->acceptedbyalliance['id']);
    $relationship_type_id    = trim($alliance->alliance->relationships->relationship->relationshiptype['id']);
    $established_date        = trim($alliance->alliance->relationships->relationship->establishedsince);
$alliances = $xml->alliances->alliance;
foreach ($alliances as $alliance) {

    // Alliance info
    $alliance_id   = trim($alliance->alliance['id']);
    $alliance_name = trim($alliance->alliance);

    // Diplomacy info
    $proposed_by_alliance_id = trim($alliance->relationships->relationship->proposedbyalliance['id']);
    $accepted_by_alliance_id = trim($alliance->relationships->relationship->acceptedbyalliance['id']);
    $relationship_type_id    = trim($alliance->relationships->relationship->relationshiptype['id']);
    $established_date        = trim($alliance->relationships->relationship->establishedsince);
Alliance ID ......: 1
Alliance NAME ....: Harmless?
Diplomacy Proposed: 454
Diplomacy Accepted: 1
Diplomacy Type ...: 4
Date Accepted  ...: 2011-10-24T05:08:35.830
-------------------------------------------------
[4x Notice: Trying to get property of non-object]
Alliance ID ......: 2
Alliance NAME ....: Danger
Diplomacy Proposed: 
Diplomacy Accepted: 
Diplomacy Type ...: 
Date Accepted  ...: 
-------------------------------------------------
...
$proposed_by_alliance_id = trim($alliance->relationships->relationship->proposedbyalliance['id']);
$accepted_by_alliance_id = trim($alliance->relationships->relationship->acceptedbyalliance['id']);
$relationship_type_id    = trim($alliance->relationships->relationship->relationshiptype['id']);
$established_date        = trim($alliance->relationships->relationship->establishedsince);
$xml = simplexml_load_file($alliances_xml); // $alliances_xml = path to file
if (!$xml) {
    throw new UnexpectedValueException(
        sprintf("Unable to load XML or it was empty. Filename given was %s", var_export($alliances_xml, true))
    );
}

$alliances = $xml->alliances->alliance;
// limit to two iterations for debugging
$alliances = new LimitIterator(new IteratorIterator($alliances), 0, 2);

foreach ($alliances as $alliance) {

    // Alliance info
    $alliance_id   = trim($alliance->alliance['id']);
    $alliance_name = trim($alliance->alliance);

    // Diplomacy info

    $proposed_by_alliance_id = trim($alliance->relationships->relationship->proposedbyalliance['id']);
    $accepted_by_alliance_id = trim($alliance->relationships->relationship->acceptedbyalliance['id']);
    $relationship_type_id    = trim($alliance->relationships->relationship->relationshiptype['id']);
    $established_date        = trim($alliance->relationships->relationship->establishedsince);

    // this is my attempt to echo every result
    echo "Alliance ID ......: $alliance_id\n";
    echo "Alliance NAME ....: $alliance_name\n";
    echo "Diplomacy Proposed: $proposed_by_alliance_id\n";
    echo "Diplomacy Accepted: $accepted_by_alliance_id\n";
    echo "Diplomacy Type ...: $relationship_type_id\n";
    echo "Date Accepted  ...: $established_date\n";
    echo "-------------------------------------------------\n";
}


Share : facebook icon twitter icon
C# how to foreach loop an XML document and modify a value

C# how to foreach loop an XML document and modify a value


By : Mohan Undapalli
Date : March 29 2020, 07:55 AM
hop of those help? I have an XML document that I want to modify the connectionstrings to. How do I do a foreach loop and in this example modify the value of LocalSqlServer?
code :
var xDoc = XDocument.Load(@"C:\xml.xml")
var node = xDoc.XPathSelectElement("//add[@name='LocalSqlServer']");
node.Attribute("connectionString").Value = "some value";
var node = xDoc.XPathSelectElement("//connectionStrings/add[@name='LocalSqlServer']");
xml parsing foreach loop + only one record inserted?

xml parsing foreach loop + only one record inserted?


By : Turman O.
Date : March 29 2020, 07:55 AM
wish of those help I cant for the life of me figure out how to get this code to process more than one record. The code works fine, it just inserts the first record and then stops. , You need to loop through the items rather than the xml itself:
code :
foreach( $xml->item as $event ) { 
  $idrandom = rand(0,99);
  $title = $event->title; 
  $description = $event->description;
  ...
}
Parsing XML in a foreach loop

Parsing XML in a foreach loop


By : pmb04
Date : March 29 2020, 07:55 AM
Hope that helps Your ThemeParkList elements are in a namespace http://schemas.datacontract.org/2004/07/WCFServiceWebRole1 - you'll need to adjust accordingly:
code :
XNamespace ns = "http://schemas.datacontract.org/2004/07/WCFServiceWebRole1";
foreach (XElement item in xdox.Descendants(ns + "ThemeParkList"))
Parsing array value with PHP in a foreach loop

Parsing array value with PHP in a foreach loop


By : SaraBlu
Date : March 29 2020, 07:55 AM
I wish this help you I solved this by following code. for 3 of them to guide by giving ideas.
code :
$datas = json_decode($content, true);
foreach($datas as $values)
 {
 $name = $values['name'];
 $value = $values['value'];
 $user_id = $values['user_id'];
 $test[]= array('user'=>$user,'name'=>$name,'value'=>$value);
 } 
}
Problem In Parsing JSON (Can't Use Foreach Loop)

Problem In Parsing JSON (Can't Use Foreach Loop)


By : Robert
Date : March 29 2020, 07:55 AM
help you fix your problem Use array_keys to get the keys and then look at the keys to decide which ones you want. This example filters keys with the word 'coupon', but you can use any filtering you want.
code :
$obj = json_decode($json, true);

print_r(array_keys($obj));
echo "\n";

foreach(array_keys($obj) as $row) {
    if ( preg_match('/.*coupons.*/', $row)) {
        if ( array_key_exists('code', $obj[$row]) ) {
            echo "Key: {$row}\n";
            echo "Code: {$obj[$row]['code']}\n";
            echo "Description: {$obj[$row]['description']}\n";
        }
    }
}
Key: getstorebylabel.coupons.0
Code: MHSURVEY
Description: 30% off Maple Holistics Products
Key: getstorebylabel.coupons.1
Code: IMTF9PRM
Description:
Key: getstorebylabel.coupons.2
Code: 68GIWR5O
Description: 68% off Spaire Lady Electric Shaver Bikini Trimmer. End Date: 05/31/2019.
Related Posts Related Posts :
  • how to run wordpress php snippet mysql update command from ssh and/ultimately cron
  • how to get xml tag by name
  • ModSecurity maximum post limits (PCRE limit errors)
  • Call controller/action in event listener
  • How to improve performance of contacting WebService?
  • PHP nest variable in echoed string that contains a HTML tag in the end
  • Multiple Ajax request for PHP framework
  • Debug Info from Moodle Plugin
  • passing variables through page
  • Passing PHP $result data to Javascript
  • cakePHP File Download was not found or not readable
  • batch waiting until script finishes
  • PHP variables and anchors in URL
  • php eTag generation using php
  • How to check whether the array is an Integer or Not?
  • Is it possible to install Doctrine without PEAR or Composer? If so, how?
  • Call view script of (parent) Abstract controller Zend
  • Curl PHP cannot display amazon
  • Symfony, getters and setters vs magic methods
  • Using 'continue' PHP instruction outside the loop
  • AJAX POST return data not appearing
  • Can I query relations using an INNER JOIN instead of two queries in Eloquent?
  • Looping through dynamic form fields and inserting into database
  • My php code can't select mysql auto_increment value
  • Store Angularjs form data in database using php
  • I want to run my sh file continuously even if I close my Putty connection
  • file_get_contents equivalent for gzipped files
  • Include PHP file with jQuery
  • php curl headers do not return from website?
  • How to find out, if facebook ID is a user, group or page
  • Connect webhost database to android database
  • preg_match get div content with class
  • Upload multiple files in Laravel 4
  • Count array numbers in multidimensional array
  • PHP Date diff with a difference
  • Search Customer by custom field in Netsuite
  • Is it possible to hide/encode/encrypt php source code and let others have the system?
  • list items to be displayed using php code and array
  • check if row exists mysqli
  • PHP errors loading MySQL
  • setup PostgreSQL with Laravel in MAMP
  • PHP - CodeIgniter Notifications
  • Encrypting a password column in a SQL database
  • New to PHP, trying to extract information from another website
  • JavaScript AmChart to Image for Email
  • Is javascript validation enough to keep my forms secure?
  • Regex extract variables from [shortcode]
  • Download a .mp3 link and save it to computer with PHP
  • Error with the ereg_replace
  • Getting the fields attached to a bundle of an entity in Drupal
  • Php how to check multiple times (within `foreach`) if values from array exists in mysql?
  • MySQL and PHP parsing strange string
  • Pull specific data from multidimensional associative array
  • How to get the original URI extension using PHP Tonic?
  • Upload videos and images from Android to PHP server?
  • Unset a multidimensional array with another multidimensional array with values than key
  • Calling a user e-mail to add to a mailto link PHP
  • Why is override_function coming back as an undefined function
  • PHP mySQLi_fetch_all: iterate through each row
  • Using pow in php
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org