GoFuckYourself.com - Adult Webmaster Forum

GoFuckYourself.com - Adult Webmaster Forum (https://gfy.com/index.php)
-   Fucking Around & Business Discussion (https://gfy.com/forumdisplay.php?f=26)
-   -   Tech How to save new created xml? (https://gfy.com/showthread.php?t=1253512)

k33n 03-23-2017 09:26 AM

How to save new created xml?
 
Need some help here.I am stuck :Oh crap

I have a XML file test.xml :
Code:

<?xml version="1.0" encoding="UTF-8"?>
<root>
        <element>
                <username>A</username>
                <about>
                        <description>random description</description>
                        <from>A place on earth</from>
                        <since>1999</since>
                </about>
                <person>
                        <gender>female</gender>
                        <age>29</age>
                        <status>single</status>
                </person>
                <profileImage>url to jpg</profileImage>
        </element>
        <element>
                <username>B</username>
                <about>
                        <description>random description</description>
                        <from>A place on earth</from>
                        <since>1999</since>
                </about>
                <person>
                        <gender>female</gender>
                        <age>35</age>
                        <status>single</status>
                </person>
                <profileImage>url to jpg</profileImage>
        </element>
        <element>
                <username>C</username>
                <about>
                        <description>random description</description>
                        <from>A place on earth</from>
                        <since>1999</since>
                </about>
                <person>
                        <gender>female</gender>
                        <age>18</age>
                        <status>single</status>
                </person>
                <profileImage>url to jpg</profileImage>
        </element>
        <element>
                <username>D</username>
                <about>
                        <description>random description</description>
                        <from>A place on earth</from>
                        <since>1999</since>
                </about>
                <person>
                        <gender>female</gender>
                        <age>22</age>
                        <status>single</status>
                </person>
                <profileImage>url to jpg</profileImage>
        </element>
        <element>
                <username>E</username>
                <about>
                        <description>random description</description>
                        <from>A place on earth</from>
                        <since>1999</since>
                </about>
                <person>
                        <gender>female</gender>
                        <age>31</age>
                        <status>single</status>
                </person>
                <profileImage>url to jpg</profileImage>
        </element>
</root>

My problem with this xml is that usernames are in alphabetical order and i want to sort them by,age for example.I use this code:
Code:

<?php


/////////////////////////////sort xml////////////////////////////////////////////////////

$url = 'test.xml';
$xml = simplexml_load_file($url);

$items = array();
foreach($xml->element as $item) {
    $items[] = $item;
};
// Custom sort on the names of the items:
usort ($items, function($a, $b ) {
    return strcmp($a->person->age[0] , $b->person->age[0]);
});

foreach ($items as $item) {
    echo $item->username . "<br/>" . $item->person->age . "<br/><br/>";
}

?>

The output:
Quote:

C
18

D
22

A
29

E
31

B
35
As you can see the elements are now sorted,but how do i save it to a new xml file,test-sorted.xml?I 've tried so many times with so many possible codes and i can't figure it out.I am lost...

lezinterracial 03-23-2017 07:35 PM

Bump for you. Maybe somebody will know better than me.


I don't program much, but this might work. Or put you on the right track.

Maybe just declare the output file
$test-sorted = 'test-sorted.xml';

and instead of using echo use file_put_contents

file_put_contents ($test-sorted,$item->username . "<br/>" . $item->person->age . "<br/><br/>", FILE_APPEND | LOCK_EX);

TitanWM 03-24-2017 11:37 PM

Why not sort the output? Have you by the assorted xml a performance advantage?

I do not understand what you are doing but this code should work:

PHP Code:

<?php
/////////////////////////////sort xml////////////////////////////////////////////////////
$url 'test.xml';

$sortXML = new cams();

$arr=$sortXML->load($url);

foreach(
$arr->element as $item) {
    
$items[] = $item;
};
usort ($items, function($a$b ) {
    return 
strcmp($a->person->age[0] , $b->person->age[0]);
});

// save array to xml
$sortXML->save('test.xml',$items);

///////////////////////////
// class
//
class cams {

    public function 
load($fname) {
        
$doc = new DOMDocument();

        if(
$doc->load($fname)) {
            
$ressimplexml_load_file($fname);
        } else {
            throw new 
Exception('error load XML');
        }

        return 
$res;
    }

    
//save array to xml
    
public function save($fname$rows) {
        
$doc = new DOMDocument('1.0','utf-8');
        
$doc->formatOutput true;

        
$elements $doc->appendChild($doc->createElement('root'));

        foreach(
$rows as $row){
            
$element=$elements->appendChild($doc->createElement('element'));

            foreach(
$row as $field_name=>$field_value) {
                
$f=$element->appendChild($doc->createElement($field_name));

                if(
$field_name=='about') {

                    foreach(
$field_value as $field_name=>$field_value) {
                        
$description=$f->appendChild($doc->createElement($field_name));
                        
$description->appendChild($doc->createTextNode($field_value));
                    }
                }

                elseif(
$field_name=='person') {
                    foreach(
$field_value as $field_name=>$field_value) {
                        
$description=$f->appendChild($doc->createElement($field_name));
                        
$description->appendChild($doc->createTextNode($field_value));
                    }
                } else {
                    
$f->appendChild($doc->createTextNode($field_value));
                }
            }
        }

        
file_put_contents($fname$doc->saveXML());
    }
}
?>

The code would still be optimized :error

k33n 03-25-2017 10:31 AM

Thank you for the code,it is working great with test.xml but the original file has more elements than the test example:
Code:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <element>
    <username>Username A</username>
    <about>
      <description>random description</description>
      <from>A place on earth</from>
      <since>1999</since>
      <another>
        <child1>this is child 1</child1>
        <child2>this is child 2</child2>
        <child3>this is child 3</child3>
      </another>

    </about>
    <persons>
      <person>
      <gender>female</gender>
      <age>29</age>
      <status>single</status>
      <body>
        <build>petite</build>
        <hairLength>shoulder length</hairLength>
        <hairColor>brown</hairColor>
        <eyeColor>green</eyeColor>
    </body>
    <decorations>
        <decoration>tatoo</decoration>
        <decoration>tongue piercing</decoration>
        <decoration>belly button</decoration>
    </decorations>
    </person>
    </persons>

    <profileImage>url to jpg</profileImage>
  </element>
  <element>
    <username>Username B</username>
    <about>
      <description>random description</description>
      <from>A place on earth</from>
      <since>1999</since>
      <another>
        <child1>this is child 1</child1>
        <child2>this is child 2</child2>
        <child3>this is child 3</child3>
      </another>
    </about>
    <persons>
      <person>
      <gender>female</gender>
      <age>35</age>
      <status>single</status>
      <body>
        <build>petite</build>
        <hairLength>shoulder length</hairLength>
        <hairColor>brown</hairColor>
        <eyeColor>green</eyeColor>
    </body>
    <decorations>
        <decoration>tatoo</decoration>
        <decoration>tongue piercing</decoration>
        <decoration>belly button</decoration>
    </decorations>
    </person>
    </persons>
    <profileImage>url to jpg</profileImage>
  </element>
  <element>
    <username>Username C</username>
    <about>
      <description>random description</description>
      <from>A place on earth</from>
      <since>1999</since>
      <another>
        <child1>this is child 1</child1>
        <child2>this is child 2</child2>
        <child3>this is child 3</child3>
      </another>
    </about>
    <persons>
      <person>
      <gender>female</gender>
      <age>35</age>
      <status>single</status>
      <body>
        <build>petite</build>
        <hairLength>shoulder length</hairLength>
        <hairColor>brown</hairColor>
        <eyeColor>green</eyeColor>
    </body>
    <decorations>
        <decoration>tatoo</decoration>
        <decoration>tongue piercing</decoration>
        <decoration>belly button</decoration>
    </decorations>
    </person>
    </persons>
    <profileImage>url to jpg</profileImage>
  </element>
  <element>
    <username>Username D</username>
    <about>
      <description>random description</description>
      <from>A place on earth</from>
      <since>1999</since>
      <another>
        <child1>this is child 1</child1>
        <child2>this is child 2</child2>
        <child3>this is child 3</child3>
      </another>
    </about>
    <persons>
      <person>
      <gender>female</gender>
      <age>22</age>
      <status>single</status>
      <body>
        <build>petite</build>
        <hairLength>shoulder length</hairLength>
        <hairColor>brown</hairColor>
        <eyeColor>green</eyeColor>
    </body>
    <decorations>
        <decoration>tatoo</decoration>
        <decoration>tongue piercing</decoration>
        <decoration>belly button</decoration>
    </decorations>
    </person>
    </persons>
    <profileImage>url to jpg</profileImage>
  </element>
  <element>
    <username>Username E</username>
    <about>
      <description>random description</description>
      <from>A place on earth</from>
      <since>1999</since>
      <another>
        <child1>this is child 1</child1>
        <child2>this is child 2</child2>
        <child3>this is child 3</child3>
      </another>
    </about>
    <persons>
      <person>
      <gender>female</gender>
      <age>31</age>
      <status>single</status>
      <body>
        <build>petite</build>
        <hairLength>shoulder length</hairLength>
        <hairColor>brown</hairColor>
        <eyeColor>green</eyeColor>
    </body>
    <decorations>
        <decoration>tatoo</decoration>
        <decoration>tongue piercing</decoration>
        <decoration>belly button</decoration>
    </decorations>
    </person>
    </persons>
    <profileImage>url to jpg</profileImage>
  </element>
</root>

The result is a sorted file but with missing elements:
Code:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <element>
    <username>Username E</username>
    <about>
      <description>random description</description>
      <from>A place on earth</from>
      <since>1999</since>
      <another>
       
       
       
      </another>
    </about>
    <persons>
      <person>
     
     
     
     
   
    </person>
    </persons>
    <profileImage>url to jpg</profileImage>
  </element>
  <element>
    <username>Username D</username>
    <about>
      <description>random description</description>
      <from>A place on earth</from>
      <since>1999</since>
      <another>
       
       
       
      </another>
    </about>
    <persons>
      <person>
     
     
     
     
   
    </person>
    </persons>
    <profileImage>url to jpg</profileImage>
  </element>
  <element>
    <username>Username C</username>
    <about>
      <description>random description</description>
      <from>A place on earth</from>
      <since>1999</since>
      <another>
       
       
       
      </another>
    </about>
    <persons>
      <person>
     
     
     
     
   
    </person>
    </persons>
    <profileImage>url to jpg</profileImage>
  </element>
  <element>
    <username>Username B</username>
    <about>
      <description>random description</description>
      <from>A place on earth</from>
      <since>1999</since>
      <another>
       
       
       
      </another>
    </about>
    <persons>
      <person>
     
     
     
     
   
    </person>
    </persons>
    <profileImage>url to jpg</profileImage>
  </element>
  <element>
    <username>Username A</username>
    <about>
      <description>random description</description>
      <from>A place on earth</from>
      <since>1999</since>
      <another>
       
       
       
      </another>
    </about>
    <persons>
      <person>
     
     
     
     
   
    </person>
    </persons>
    <profileImage>url to jpg</profileImage>
  </element>
</root>

I tried to adapt the code but with no result. :( Can you please give me a solution? Thank you!
Quote:

Originally Posted by TitanWM (Post 21653626)
Why not sort the output? Have you by the assorted xml a performance advantage?

I believe so.Maybe i am talking nonsense but if i sort the output,would be done every time the page loads.Instead i am sorting the xml file and save it for future use.

sarettah 03-25-2017 07:03 PM

Hardcoded the "root" and "element" tags in there, so it is working from the structure of your test file in that regard,

Code:

<?php
// mainline
 
echo "Start of run " . date("M d Y H:i:s", time()) . "<br>\n";
flush();

// define sorter object
$xmlobj=new hd_xml_sorter();

// input file - valid xml file or url to xml feed
$xmlobj->inputfile='test.xml';

// output file name - include path if not the current folder
$xmlobj->outputfile='new_sorted.xml';

// sort fields - order of fields to sort by , type n=numeric, s=string
$xmlobj->sortfields=[['name'=>'age','type'=>'n'],['name'=>'username','type'=>'s']];

// main sort order - first field is controlling field asc is ascending, des is descending. defaulkts ot ascending
$xmlobj->sortorder='asc';

// call to main file process
$xmlobj->hd_sort_file();

echo "Finished " . date("M d Y H:i:s", time()) . "<br>\n";
if(!empty($xmlobj->error_message))
{
  echo "There were errors:<br>\n" . $xmlobj->error_message . "<br>\n";   
}
echo "Processed " . $xmlobj->process_count . " input records<br>\n";
echo "wrote " . $xmlobj->records_written . " output records<br>\n";

// end of mainline

class hd_xml_sorter
{
  public $inputfile='';
  public $outputfile='xml_output.xml';
  public $sortfields=[];
  public $sortorder='asc';
  public $records_written=0;
  public $process_count=0;
  public $error_message='';
   
  private $sortwork=[];
  private $sortvals=[];
  private $inrec='';
 
  public function hd_sort_file()
  {
    if(!empty($this->inputfile))
    {
      $this->hd_get_xml_file($this->inputfile);
      if($this->inrec)
      {
        $this->hd_process_xml($this->sortwork,$this->sortfields);
      }
      if(count($this->sortwork)>0)
      {
        $this->hd_sort_xml_file();
      }
      if(count($this->sortwork)>0)
      {
        $this->hd_write_xml_file();
      }
    }
    else
    {
      $this->error_message .="No input filename was given<br>\n";
    }
  }

  private function hd_get_xml_file()
  {
    $this->inrec=simplexml_load_file($this->inputfile);
    if(!$this->inrec)
    {
      $this->error_message .="Could not get xml feed: " . $this->inputfile . "<br>\n";
    }
  }
 
  private function hd_process_xml($xmlrec='')
  {
    $proc_cnt=0;
    foreach($this->inrec as $inrec)
    {
      $this->sortvals=array_fill(0,count($this->sortfields),'');
      $this->sortwork[]['sortkey']='';
      $outrec='';
      $outrec=$this->hd_iterate_xml($inrec, $outrec);
      for($i=0;$i<count($this->sortvals);$i++)
      {
        $this->sortwork[count($this->sortwork)-1]['sortkey'] .=$this->sortvals[$i] . "_";
      }     
      $this->sortwork[count($this->sortwork)-1]['body']=$outrec;
      $this->process_count++;
    }
  }

  private function hd_iterate_xml($inrec, $outrec='')
  {
    foreach($inrec as $key=>$value)
    {
      $key=str_replace("\n","",$key);
      if(count($value)>0)
      {
        $workrec='';
        $workrec .=$this->hd_iterate_xml($value, $workrec);
        $outrec .="<" . $key . ">" . $workrec . "</" . $key . ">\n";;
      }
      else
      {
        $outrec .="<" . $key . ">" .  trim($value) . "</" . $key . ">\n";
        $cntr=0;
        foreach($this->sortfields as $field)
        {
          if($field['type']=='s')
          {
            $val2use='';
          }
          else
          {
            $val2use='0';
          }
          //echo "field name=" . $field['name'] . " key=" . $key . "<br>\n";
          if($key==$field['name'])
          {       
            if($field['type']=='s')
            {
              $val2use=trim($value);
            }
            else
            {
              $val2use=trim(strval($value));
            }           
            $this->sortvals[$cntr]=$val2use;
          }
          $cntr++;
        }
      }
    }
    return $outrec;
  }

  private function hd_sort_xml_file()
  {
    foreach ($this->sortwork as $key => $row)
    {
      $sortkey[]['key']  = $row['sortkey'];
    }
    if($this->sortorder=='des')
    {
      array_multisort($sortkey, SORT_DESC, $this->sortwork);
    }
    else
    {
      array_multisort($sortkey, SORT_ASC, $this->sortwork);
    }
  }

  private function hd_write_xml_file()
  {
    $outfile=fopen($this->outputfile,'w');
    fwrite($outfile,'<' . '?xml version="1.0" encoding="utf-8" ?' . ">\n");
    fwrite($outfile,"<root>\n");
    for($i=0;$i<count($this->sortwork);$i++)
    {
      fwrite($outfile,"<element>\n");
      fwrite($outfile,$this->sortwork[$i]['body']);
      fwrite($outfile,"</element>\n");
      $this->records_written++;       
    } 
    fwrite($outfile,"</root>\n");
    fclose($outfile);
  } 
}

?>

.

k33n 03-26-2017 05:42 AM

Hey Sarettah,

It works but the &amp; in the url are copied as & and the new xml is not accessible neither with the script or browser.
Code:

http://domain.com/?aff=0000&amp;prg=rev&amp;profile=username
become
Code:

http://domain.com/?aff=0000&prg=rev&profile=username
So now i have the sorted file but can't use it.After some research i found that encoding="utf-8" should take care o this but...is not.Any ideas?
Thank you!

sarettah 03-26-2017 06:41 AM

Quote:

Originally Posted by k33n (Post 21656227)
Hey Sarettah,

It works but the &amp; in the url are copied as & and the new xml is not accessible neither with the script or browser.

So now i have the sorted file but can't use it.After some research i found that encoding="utf-8" should take care o this but...is not.Any ideas?
Thank you!

You have lost me a little bit here.

Is that url in the xml file? Or ??

&amp is the html special character for &. I am not sure where you are seeing that.

.

sarettah 03-26-2017 06:55 AM

I just tested against my chaturbate xml feed url and it did NOT change urls in the file on me.

The iframes in the chaturbate feed all have the &amp; in them in the original. They have them in there before the sort and after the sort.

The chat room urls do not have &amp; in the original, they just have &. They appear the same way in the sort as in the original.

Iframe from the original:

Code:

<iframe src='https://chaturbate.com/affiliates/in/?tour=XXXX&amp;campaign=XXXXX&amp;track=embed&amp;room=killer__tits&amp;bgcolor=white' height=528 width=850 style='border: none;'></iframe>
From the sorted file:

Code:

<iframe src='https://chaturbate.com/affiliates/in/?tour=XXXX&amp;campaign=XXXXX&amp;track=embed&amp;room=killer__tits&amp;bgcolor=white' height=528 width=850 style='border: none;'></iframe>
Chat url from the original:

Code:

<chat_room_url>
https://chaturbate.com/affiliates/in/?tour=XXXX&campaign=XXXXX&track=default&room=killer__tits
</chat_room_url>

Chat url from the sorted file:

Code:

<chat_room_url>
https://chaturbate.com/affiliates/in/?tour=XXXX&campaign=XXXXX&track=default&room=killer__tits
</chat_room_url>

The code I put up should not be changing anything.

However, if you are looking at things in a browser then the &amp; could show as & because that is what an html entity does. You might need to look at the source to see the actual data properly.

Anyway, let me know where you are seeing what you are seeing.

.

sarettah 03-26-2017 08:39 AM

I have checked all sorts of stuff and even re-written the sort to hanlde everything as xml object rather than an array but no luck. The test stuff you sent me still comes out wrong.

Here is a fix, it is not elegant at all. It addresses the issue you have explicitly and hopefully will work until we figure out wtf is happening:

Replace the hd_iterate_xml function with this:

Code:

  private function hd_iterate_xml($inrec, $outrec='')
  {
    foreach($inrec as $key=>$value)
    {
      $key=str_replace("\n","",$key);
      if(count($value)>0)
      {
        $workrec='';
        $workrec .=$this->hd_iterate_xml($value, $workrec);
        $outrec .="<" . $key . ">" . $workrec . "</" . $key . ">\n";;
      }
      else
      {
        // workaround for k33n issue
        if(trim($key)=='chatRoomUrl')
        {
          $value=htmlspecialchars($value);
        }
        $outrec .="<" . $key . ">" .  trim($value) . "</" . $key . ">\n";
        $cntr=0;
        foreach($this->sortfields as $field)
        {
          if($field['type']=='s')
          {
            $val2use='';
          }
          else
          {
            $val2use='0';
          }
          //echo "field name=" . $field['name'] . " key=" . $key . "<br>\n";
          if($key==$field['name'])
          {       
            if($field['type']=='s')
            {
              $val2use=trim($value);
            }
            else
            {
              $val2use=trim(strval($value));
            }           
            $this->sortvals[$cntr]=$val2use;
          }
          $cntr++;
        }
      }
    }
    return $outrec;
  }


TitanWM 03-26-2017 09:41 AM

Quote:

Originally Posted by sarettah (Post 21656461)
I have checked all sorts of stuff and even re-written the sort to hanlde everything as xml object rather than an array but no luck. The test stuff you sent me still comes out wrong.

Here is a fix, it is not elegant at all. It addresses the issue you have explicitly and hopefully will work until we figure out wtf is happening:

Your first code ist elegant :thumbsup
But to use for chaturbate xml-feed you must set in the element_name "iframe" the "height" and "width" values in single quotes:

str_replase " height=528 width=850 " with " height='528' width='850' "

k33n 03-26-2017 09:55 AM

Quote:

Originally Posted by sarettah (Post 21656461)
Here is a fix, it is not elegant at all.

Don't know about elegance but it does the trick.Thank you :)


All times are GMT -7. The time now is 11:49 PM.

Powered by vBulletin® Version 3.8.8
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
©2000-, AI Media Network Inc