Jump to content

XML create a tag element with attribute and give it a value.


Miko

Recommended Posts

Hello,

 

I have made a PHP script that will feed an existing XML file. The file stores song details like, title, name of singer etc ...

Now the file structure is like this for the moment:

 

<?xml version="1.0" encoding="UTF-8"?>
<music>
  <song>
    <title>Without me</title>
    <artist>Eminem</artist>
    <url>songs/coreIssues.mp3</url>
    <image>img/den.jpg</image>
    <discspeed>11</discspeed>
  </song></music>

 

But I need it to be:

 

<?xml version="1.0" encoding="UTF-8"?>
<music>
  <song mainTitle="Eminem - Without me">
    <title>Without me</title>
    <artist>Eminem</artist>
    <url>songs/coreIssues.mp3</url>
    <image>img/den.jpg</image>
    <discspeed>11</discspeed>
  </song></music>

 

I need it to be like that so if I want to delete a song from the list I just check for the element which will have a unique mainTitle and then delete that element with all it's details.

 

Now, I've searched on Google for some solutions but didn't find any yet.

 

Anyone here knows how to do this?

 

Thanks!

You don't need that mainTitle thing. Watch this:

$xml = new DOMDocument();
$xml->loadXML(

  
    Without me
    Eminem
    songs/coreIssues.mp3
    img/den.jpg
    11
  

XML
);

$title = "Without me";
$artist = "Eminem";

$xpath = new DOMXPath($xml);
foreach ($xpath->query('//song[title="' . htmlentities($title) . '" and artist="' . htmlentities($artist) . '"]') as $node) {
$node->parentNode->removeChild($node);
}

echo $xml->saveXML();

 

Though I suggest using ID numbers instead of relying on names.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.