2

I'm trying to search for a way to easily modify xml in php. The PHP documentation is very confusing regarding how to easily manipulate xml. I like how SimpleXml allows for easily finding tags/attributes, but it doesn't seem to allow you to easily add child trees, or replace existing ones.

Any suggestion on what to use?

My use case includes:

  • Finding specific tag elements with specific attributes.
  • Replacing a found element subtree.
  • Using child trees which were generated from xml text.
EmpireJones
  • 2,936
  • 4
  • 29
  • 43
  • possible duplicate of [Best XML Parser for PHP](http://stackoverflow.com/questions/188414/best-xml-parser-for-php/3616044#3616044) and [PHP what is the best approach to using XML?](http://stackoverflow.com/questions/2060346/php-what-is-the-best-approach-to-using-xml-need-to-create-and-parse-xml-response) – Gordon Dec 03 '10 at 07:43
  • Your use cases are very vague, can you give some more details? – salathe Dec 03 '10 at 10:28
  • Class for simple XML parsing: http://www.phpclasses.org/package/4-PHP-Arbitrary-XML-parser-.html – nadavmiller.com Dec 03 '10 at 08:08

2 Answers2

9

I use XPATH and SimpleXML to change my file. A little example...

The xml file:

<?xml version="1.0"?>

<forum uri="http://myforum.org/index.php">

    <item id="1">
        <title>First Post!!!</title>
        <link>http://myforum.org/index.php/m/1</link>
        <description>hello I'm fabio</description>
    </item>

    <item id="2">
        <title>Re: Second post!!!</title>
        <link>http://myforum.org/index.php/m/2</link>
        <description>2nd good message.</description>
    </item>
</forum>

And PHP handler:

<?php

$forum = simplexml_load_file('forum.xml');

/* some xpath EXAMPLES */   
/* catch all items in forum */
$result = $forum->xpath('/forum/item');
/* catch all links */
$result = $forum->xpath('//link');
/* search for "Re:" in title and returns the item's id */
$result = $forum->xpath('//item[contains(title, "Re:")]/@id');
/* catch > 10 length items and returns the item's title*/
$result = $forum->xpath('//item[string-length(description) > 10]/title');

$forum->item[1]->title['url']   = "http://goo.gl/";     /* this add a an attribute */
$forum->item[0]->foo            = "newnode";            /* this add content */
$forum->item[0]->foo['attrib']  = 10;                   /* this add a another value */
$forum->addChild('element_name', 'value');              /* this is a new element /*

 /* delete value */
unset($forum->item[0]);


// XML rendering
echo $forum->asXML();
Fabio Mora
  • 5,339
  • 2
  • 20
  • 30
0

i have used sometime the SimpleXML to read XML files from PHP and the DOM to create them, i let you here a couple of nice liks about the matter.

Enjoy.

SubniC
  • 9,807
  • 4
  • 26
  • 33