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!

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.