A Simple Program to Crud Node and Node Values of Xml File

A simple program to CRUD node and node values of xml file

If your XML is really that simple, you can use SimpleXML to CRUD it. SimpleXml will parse the XML into a tree structure of SimpleXmlElements. In a nutshell, you use it like this:

// CREATE
$config = new SimpleXmlElement('<settings/>');
$config->setting1 = 'setting1 value';
$config->saveXML('config.xml');

// READ
$config = new SimpleXmlElement('config.xml');
echo $config->setting1;
echo $config->asXml();

// UPDATE
$config->setting1 = 'new value';
$config->setting2 = 'setting2 value';
echo $config->asXml();

// DELETE
unset($config->setting1);
$config->setting2 = NULL;
echo $config->asXML();
unlink('config.xml');

Please refer to the PHP manual for further usage examples and the API description.

On a sidenote, if you really just have key/value pairs, you could also use a plain old PHP array to store them or a key/value store like DBA or even APC and memcached with a long ttl.

I want to edit an XML file using PHP

As was suggested in Gordon's answer, I would load the XML file into SimpleXML, append the node and then sort it.

I've commented the code below to explain it step-by-step.

<?php

// Open the XML file
$xml = file_get_contents("captions.xml");
// SimpleXml is an "easy" API to manipulate XML
// A SimpleXmlElement is any element, in this case it will be the <body>
// element as it is first in the file.
$timestamps = new SimpleXmlElement($xml);

// Add our new time entry to the <div> element inside <body>
$timestamps->div->addChild("p", null);
// Get the index of the last element (the one we just added)
$index = $timestamps->div->p->count()-1;
// Add a time attribute to the element we just added
$e = $timestamps->div->p[$index];
$e->addAttribute("time", "00:00:12");
// Replace it with the new one (with a time attribute)
$timestamps->div->p[$index] = $e;

// Sort the elements by time (I've used bubble sort here as it's in the top of my head)
// Make sure you're setting this here or in php.ini, otherwise we get lots of warnings :)
date_default_timezone_set("Europe/London");

/**
* The trick here is that SimpleXmlElement returns references for nearly
* everything. This means that if you say $c = $timestamps->div->p[0], changes
* you make to $c are made to $timestamps->div->p[0]. It's the same as calling
* $c =& $timestamps->div->p[0]. We use the keyword clone to avoid this.
*/
$dates = $timestamps->div->children();
$swapped = true;
while ($swapped) {
$swapped = false;
for ($i = 0; $i < $dates->count() - 1; $i++) {
$curTime = clone $dates[$i]->attributes()->time;
$nextTime = clone $dates[$i+1]->attributes()->time;

// Swap if current is later than next
if (strtotime($curTime) > strtotime($nextTime)) {
$dates[$i]->attributes()->time = $nextTime;
$dates[$i+1]->attributes()->time = $curTime;
$swapped = true;
break;
}
}
}

// Write back
echo $timestamps->asXml();
//$timestamps->asXml("captions.xml");

Update data in XML file using PHP

Have a look at SimpleXML. You can access and change your elements like an array then:

<?php 
$string = '<books>
<book>
<Name>BookName1</Name>
<Author>author1</Author>
</book>
<book>
<Name>BookName2</Name>
<Author>author2</Author>
</book>
</books>';

$xml = simplexml_load_string($string);
$xml->book[0]->Name= "Something else"; // or BookName2
echo $xml->asXML();
?>

Trying to parse this xml feed using php

You can use $variable['attribute_name'] to read the attribute data and for elements with dash and other characters in between the letters you can enclose it with braces and single quotes like I have done for the operating-systems element.

<?php
$url = 'http://www.shinyloot.com/feeds/games_on_sale';
$xml = simplexml_load_string(file_get_contents($url));
foreach ($xml->games->game as $game)
{
$operating_system = array();
foreach ($game->{'operating-systems'}->os as $os)
$operating_system[] = $os;

if (!in_array("Linux", $operating_system))
continue;
echo "Title: ", $game['title'], "\n";
echo "URL: ", $game['url'], "\n";
echo "MRSP: ", $game->mrsp, "\n";
echo "Price: ", $game->price, "\n";
echo "Discount: ", $game->{'discount-pct'}, "%\n";
echo "Cover Image: ", $game->{'cover-image'}, "\n";
echo "Header Image: ", $game->{'header-image'}, "\n";
echo "Available for:\n";
foreach ($operating_system as $os)
{
echo $os, "\n";
}
echo "==================================================\n\n";
}

An alternative way would be like this:

$operating_system = json_decode(json_encode($game->{'operating-systems'}), true);
if (!in_array("Linux", $operating_system['os']))
continue;

Basically it transforms the result in JSON then convert it back into a simple associative array.

Simplest XML Node Editor for PHP

SimpleXML

$doc = simplexml_load_file('http://example.com/example.xml');

// Note the SimpleXMLElement is the root node, ie <node>
$doc->node2 = 'new content';

$doc->asXml('new-filename.xml'); // Note, saves locally
// or
$xmlString = $doc->asXml();

Search XML file *based* on search criteria and remove nodes - ASP or PHP

In terms of XPath (1.0) which ASP.NET and PHP support with the normal installations you can use /Items/book[contains(title, 'Beginning') or contains(title, 'Advance')]. Note that XML node names and therefore XPath expressions are case-sensitive, your sample is not well-formed XML as it has a start tag <Items> but an end tag </items>.

As for code to remove nodes with ASP.NET, try along the following lines:

XmlDocument doc = new XmlDocument();
doc.Load("input.xml");
XmlNodeList booksToRemove = doc.SelectNodes("/Items/book[contains(title, 'Beginning') or contains(title, 'Advance')]");
for (int i = booksToRemove.Length - 1; i >= 0; i--) {
booksToRemove[i].ParentNode.RemoveChild(booksToRemove[i]);
}
doc.Save("output.xml");

How to read in XML strings as variables?

You can use SimpleXmlIterator. That's really easy to use and you will be able to perform a foreach on the object you will get.

Library source

For example with file_get_contents or replace with curl if you prefer:

    $feed = new SimpleXmlIterator(file_get_contents('http://www.dictionaryapi.com/api/v1/references/collegiate/xml/gobabola?key=135a6187-af83-4e85-85c1-1a28db11d5da'));
foreach ($feed->suggestion as $suggestion) {
echo $value;
}


Related Topics



Leave a reply



Submit