B
B
Bogdan Gerasimenko2018-06-29 11:22:31
PHP
Bogdan Gerasimenko, 2018-06-29 11:22:31

Is it possible to update part of an XML file via PHP?

There is a view file (simplified):

<products>
  <product id="1">
    <name>Test 01</name>
    <price>123</price>
  </product>
  ...
  <product id="999">
    <name>Test 999</name>
    <price>456</price>
  </product>
</products>

It is necessary, for example, to change . The simplest solution is to completely generate the file every time it is edited (information is taken from the database). Is there a PHP library that allows you to jump to a string and change, for example, ? Or can you just read the contents of the file into a string and use str_replace to change the desired sections? (file formatting is lost). What are some ideas about editing XML online? <product id="123">
<product id="123"><price>456</price>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nozzy, 2018-06-29
@Kleindberg

$products = simplexml_load_file('your_file.xml');
$products[0]->price = 321;
$products->asXML('your_file.xml');

R
rPman, 2018-06-30
@rPman

If you generate the xml file, you can guarantee, for example, its formatting (prohibit the transfer of data that is critical for you to new lines), in this case, a lot of situations can be handled with a simple search and replace.
In difficult situations, when you need to look for exactly where and what to replace, you can parse xml yourself, line by line, there are even ready-made methods for this
https://secure.php.net/manual/ru/ref.xml.php
i.e. you parse xml line by line to find the desired line, and write as with a regular text file, line by line, replacing the necessary data on the fly.
ps if you have large data that such optimization is required (if the option described in the next answer does not suit you), then ... change the logic of your program, .. xml (or for example json) is generally the most inappropriate tool for storage.

A
Alexander Komarchuk, 2018-07-01
@AlexanderKomarchouk

What is the point? It's not a database, it's a text file.
A file that will be completely overwritten with any change.
If you store something in bulky XML, and you are worried about the possible load, then divide them according to some parameters, let your file system have not one large file, but the N number of smaller files.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question