Iterate through items from SOAP-xml result in php - php

i'm trying with no success to iterate throug an xml string. I did it before and it worked fine.
I get this from a SOAP server doing this:
$lr = $client->__doRequest($request, $url, $action, $version);
dd($lr);
I get this:
Too long to be here. It's on pastebin
When i try this:
$xml = new \DOMDocument();
$xml->loadXML($lr);
$i = 0;
while(is_object($productos = $xml->getElementsByTagName('Productos')->item($i))) {
foreach($productos->childNodes as $nodename) {
echo $i.": ".$nodename->nodeName." - ".$nodename->nodeValue."<br>";
}
$i++;
}
I get this: Result with products
Now, i want to do something like this:
foreach ($productos as $producto) {
$referencia_dist = trim($producto->IdProducto);
$mpn = trim($producto->PartNumber);
$ean = trim($producto->UpcCode);
and son on....
}
But i get stacked here. Any hints???

OK! Got the solution! It is easier than i thought... Perhaps, that's the reason why i didn't find it...
while(is_object($productos = $xml->getElementsByTagName('Productos')->item($i))){
$nombre = "";
$IdCategoria = "";
foreach($productos->childNodes as $producto)
{
switch ($producto->nodename){
case 'IdProducto':
$IdProducto = $producto->nodeValue;
case 'IdTarifa':
$IdTarifa = $producto->nodeValue;
case 'MostrarComparadores':
$MostrarComparadores = $producto->nodeValue;
case....
}

Related

Iterating over an XML file in PHP

I'm using Laravel to parse an XML file and store it into the DB. Now, it's probably some sort of a stupid mistake I can't put my finger on, but I would really appreciate if someone could check the code and the weird results I'm getting.
The XML has a deep and complex structure, here's a little piece from that's bugging me:
I'm dumping the $nizXMLsp in the end to see what's inside the array of objects:
public function upload(){
$dom = new DomDocument();
$nizBaza = DB::table('offers')->orderBy('id', 'DESC')->first();
$nizXML = array();
$objekat = new stdClass();
$dom->load("storage/X_Lista.xml");
$domXpath = new DomXPath($dom);
$upit = $domXpath->query('//offer');
foreach($upit as $of){
$objekat->Time = $of->getAttribute('Time');
$objekat->Date = $of->getAttribute('Date');
$objekat->betRound = $of->getAttribute('betRound');
$objekat->timestamp = $of->getAttribute('timestamp');
array_push($nizXML, $objekat);
}
if(is_null($nizBaza) or $nizBaza->id != $nizXML[0]->betRound) {
$kolo = new Offer();
$kolo->id = $objekat->betRound;
$kolo->ts = $objekat->Date . " " . $objekat->Time;
$kolo->posix = $objekat->timestamp;
$kolo->save();
//
$nizBaza = DB::table('sportovi')->get();
$nizXMLsp = array(); $objekat_sp = new stdClass();
foreach($dom->getElementsByTagName('sport') as $k=>$v){
$objekat_sp->id = $v->getAttribute('id');
$objekat_sp->name = $v->getAttribute('name');
$objekat_sp->betRound = $v->parentNode->getAttribute('betRound');
$nizXMLsp[$k] = $objekat_sp;
}
}
elseif($nizBaza->id == $nizXML[0]->betRound){
echo 'break1';
exit;
}
else {
echo 'break2';
exit;
}
return var_dump($nizXMLsp);
}
Now, what I see in the end is this:
instead of 4 objects with different sets of data, I get 4 objects with same set of data (all of the data comes from the last node). What could it be?
Possibly a very simple adjustment. Just reset $objekat_sp inside the loop:
foreach($dom->getElementsByTagName('sport') as $k=>$v){
$objekat_sp = "";
$objekat_sp->id = $v->getAttribute('id');
$objekat_sp->name = $v->getAttribute('name');
$objekat_sp->betRound = $v->parentNode->getAttribute('betRound');
$nizXMLsp[$k] = $objekat_sp;
}
Move
$objekat = new stdClass();
and
$objekat_sp = new stdClass();
inside their respective foreach loops.
Right now you're pushing the same object (after modifying its properties) into the array multiple times.

PHP Array & XML Can't get all content

I'm tring to get all content from this xml: https://api.eveonline.com/eve/SkillTree.xml.aspx
To save it on a MySQL DB.
But there are some data missing...
Could any1 that understand PHP, Array() and XML help me, please?
This is my code to get the content:
<?php
$filename = 'https://api.eveonline.com/eve/SkillTree.xml.aspx';
$xmlbalance = simplexml_load_file($filename);
$skills = array();
for ($x=0;$x<sizeOf($xmlbalance->result->rowset->row);$x++) {
$groupName = $xmlbalance->result->rowset->row[$x]->attributes()->groupName;
$groupID = $xmlbalance->result->rowset->row[$x]->attributes()->groupID;
for ($y=0;$y<sizeOf($xmlbalance->result->rowset->row[$x]->rowset->row);$y++) {
$skills[$x]["skillID"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->attributes()->typeID;
$skills[$x]["skillName"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->attributes()->typeName;
$skills[$x]["skillDesc"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->description;
$skills[$x]["skillRank"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rank;
$skills[$x]["skillPrimaryAtr"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->requiredAttributes->primaryAttribute;
$skills[$x]["skillSecondAtr"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->requiredAttributes->secondaryAttribute;
$o = 0;
for ($z=0;$z<sizeOf($xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->row);$z++) {
if ($xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->attributes()->name == "requiredSkills") {
$skills[$x]["requiredSkills"]["".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->row[$z]->attributes()->typeID] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->row[$z]->attributes()->skillLevel;
$o++;
}
}
}
}
echo '<pre>'; print_r($skills); echo '</pre>';
?>
If you go to the original XML (link), at line 452, you will see:
<row groupName="Spaceship Command" groupID="257">
And that isn't show in my array (link)...
That is one thing that i found that is missing...
I think that probally have more content that is missing too..
Why? How to fix it, please?
Thank you!!!
You will only get a total of sizeof($xmlbalance->result->rowset->row) records. Because, in your 2nd for loop, you are basically storing your result in the same array element that is $skills[$x].
Try this (I also higly encourage you to be as lazy as you can when you write code - by lazy I mean, avoid repeating / rewriting the same code over and over if possible) :
$filename = 'https://api.eveonline.com/eve/SkillTree.xml.aspx';
$xmlbalance = simplexml_load_file($filename);
$skills = array();
foreach ($xmlbalance->result->rowset->row as $row)
{
$groupName = $row->attributes()->groupName;
$groupID = $row->attributes()->groupID;
foreach ($row->rowset->row as $subRow)
{
$skill['skillID'] = (string) $subRow->attributes()->typeID;
$skill['skillName'] = (string) $subRow->attributes()->typeName;
$skill['skillDesc'] = (string) $subRow->description;
$skill['skillRank'] = (string) $subRow->rank;
$skill['skillPrimaryAtr'] = (string) $subRow->requiredAttributes->primaryAttribute;
$skill['skillSecondAtr'] = (string) $subRow->requiredAttributes->secondaryAttribute;
foreach ($subRow->rowset as $subSubRowset)
{
if ($subSubRowset->attributes()->name == 'requiredSkills')
{
foreach ($subSubRowset->row as $requiredSkill)
{
$skill['requiredSkills'][(string) $requiredSkill->attributes()->typeID] = (string) $requiredSkill['skillLevel'];
}
}
}
$skills[] = $skill;
}
}
print_r($skills);

variable in loop function

I want to get the value from a loop function but am stuck in this problem, maybe you guys can give me help, thanks.
I define the parameters here
$my_value1 = "Order";
$my_value2 = "Transaction";
$my_value3 = "Name";
$doc2 = new DOMDocument();
$doc2->load( 'GetOrders.xml' );
$info2 = $doc2->getElementsByTagName( $my_value1 );
foreach( $info2 as $Type2 )
{
$ebayOrder = $Type2->getElementsByTagName($my_value2);
foreach($ebayOrder as $Type3)
{
echo getMyValue("OrderLineItemID",$Type3); echo '</br>';
}
The problem is that I want to call something like set the my_value2 in the loop and call something like
getMyValue($my_value3,$Type3)
Is possible to rewrite the function, so I can always call using the new parameter?
thanks in advance,
Mike
You can use variables as a parts of the names of other variables. Try with:
for ($i = 1; $i <= 3; $i++) {
$my_value = ${'my_value' . $i};
$info2 = $doc2->getElementsByTagName( $my_value );
}

Array within an array using Facebook Graph APi

I have been working on this problem for the last 2 days, searched over and over again .. nothing. Understanding that I am not an expert here - it's good! lol
I am trying to get the information found in the link below;
https://graph.facebook.com/570215713050551_4508656/comments/?fields=likes.fields(id,username,name,profile_type)
to then export into a csv.
Now I have current numerous other api tools, but this one has stumped me.
Basically, need to get the data foreach then run that again plus do the "next" paging etc.
Totally lost here.
My current code is here.
<?php
//Export and Download the Liker Data from each comment here ..
$id = $_GET['data'];
$commentor = $_GET['commentor'];
$toget = 'https://graph.facebook.com/'.$id.'/comments/?fields=likes.fields(id,username,name,profile_type)';
$data = #file_get_contents($toget);
$data = json_decode($data,true);
if($data['data'] == FALSE){
echo "gay!";
die;
}
$alldata = array();
function moredata($data){
global $alldata;
foreach ($data["data"] as $eachdata){
$onedata['id'] = $eachdata['id'];
foreach ($eachdata["likes"] as $ex){
$onedata['uid'] = $$ex['data'][0]['id'];
$onedata['name'] = $ex['data'][0]['name'];
$onedata['username'] = $ex['data'][0]['username'];
$onedata['profile_type'] = $ex['data'][0]['profile_type'];
//$onedata['link'] = $eachdata['link'];
}
$alldata[] = $onedata;
$onedata = array();
}
if (array_key_exists('next', $data['paging'])) {
$nextpagelink = $data['paging']['next'];
$nextdata = json_decode(file_get_contents($nextpagelink),true);
moredata($nextdata);
}
}
moredata($data);
... ETC ETC to get out the csv
Any help here would be amazing! Thanks guys.
It was little tricky but can be solved the issue with nested recursion.
I have tried your code and made few changes and it worked. Check the code below
$alldata = array();
$arrlikedata = array();
function moredata($data){
global $alldata;
global $arrlikedata;
foreach ($data["data"] as $eachdata)
{
$onedata['id'] = $eachdata['id'];
if(isset($eachdata["likes"])){
$onedata['likes'] = more_like_data($eachdata["likes"]);
}
else{
$onedata['likes'] = array();
}
$alldata[] = $onedata;
$arrlikedata = array();
}
if (array_key_exists('next', $data['paging'])) {
$nextpagelink = $data['paging']['next'];
$nextdata = json_decode(file_get_contents($nextpagelink),true);
moredata($nextdata);
}
}
function more_like_data($likedata)
{ global $alldata;
global $arrlikedata;
if(isset($likedata["data"])){
foreach ($likedata["data"] as $ex){
if(isset($ex)){
$onedata1['uid'] = $ex['id'];
$onedata1['name'] = $ex['name'];
$onedata1['username'] = (isset($ex['username']))?$ex['username']:'';
$onedata1['profile_type'] = $ex['profile_type'];
$arrlikedata[] = $onedata1;
$onedata1 = array();
}
}
}
if(isset($likedata['paging'])){
if (array_key_exists('next', $likedata['paging']))
{
$nextpagelink = $likedata['paging']['next'];
$nextlikedata = json_decode(file_get_contents($nextpagelink),true);
return more_like_data($nextlikedata);
}
else{
return $arrlikedata;
}
}
else{
return $arrlikedata;
}
}
moredata($data);
print "<pre>";
print_r($alldata);
print "</pre>";

Show XML tag full path with php

Let's assume we want to process this Feed: http://tools.forestview.eu/xmlp/xml_feed.php?aid=1094&cid=1000
I'm trying to show the nodes of an XML file this way:
deals->deal->dealsite
deals->deal->deal_id
deals->deal->deal_title
This is in order to be able to process feeds that we don't know what their XML tags are. So we will let the user choose that deals->deal->deal_title is the Deal Title and will recognize it that way.
I have been trying ages to do this with this code:
class HandleXML {
var $root_tag = false;
var $xml_tags = array();
var $keys = array();
function parse_recursive(SimpleXMLElement $element)
{
$get_name = $element->getName();
$children = $element->children(); // get all children
if (empty($this->root_tag)) {
$this->root_tag = $this->root_tag.$get_name;
}
$this->xml_tags[] = $get_name;
// only show children if there are any
if(count($children))
{
foreach($children as $child)
{
$this->parse_recursive($child); // recursion :)
}
}
else {
$key = implode('->', $this->xml_tags);
$this->xml_tags = array();
if (!in_array($key, $this->keys)) {
if (!strstr('>', $key) && count($this->keys) > 0) { $key = $this->root_tag.'->'.$key; }
if (!in_array($key, $this->keys)) {
$this->keys[] = $key;
}
}
}
}
}
$xml = new SimpleXMLElement($feed_url, null, true);
$handle_xml = new HandleXML;
$handle_xml->parse_recursive($xml);
foreach($handle_xml->keys as $key) {
echo $key.'<br />';
}
exit;
but here's what I get instead:
deals->deal->dealsite
deals->deal_id
deals->deal_title
See on 2nd and 3rd line the deal-> part is missing.
I have also tried with this code: http://pastebin.com/FkPWXF64 but it's definitely not the best way to go and it doesn't always work.
No matter how many times I couldn't do it.
In one of my sites I use a little different approach to handle xml feed. In your case it would look like:
$xml = simplexml_load_file("http://tools.forestview.eu/xmlp/xml_feed.php?aid=1094&cid=1000");
foreach($xml->{'deal'} as $deal)
{
$dealsite = $deal->{'dealsite'};
$dael_id = $deal->{'dael_id'};
$deal_title = $deal->{'deal_title'};
$deal_url = $deal->{'deal_url'};
$deal_city = $deal->{'deal_city'};
$deal_category = $deal->{'deal_category'};
// and so on for the rest
// do some stuff with the variables like insert into MySQL
}

Categories