tags:

views:

38

answers:

1
<data>
    <gig id="1">
    <date>December 19th</date>
    <venue>The Zanzibar</venue>
    <area>Liverpool</area>
    <telephone>Ticketline.co.uk</telephone>
    <price>£6</price>
    <time>Time TBA</time>
</gig>
<gig id="2">
    <date>Sat. 16th Jan</date>
    <venue>Celtic Connection, Classic Grand</venue>
    <area>Glasgow</area>
    <telephone>0141 353 8000</telephone>
    <price>£17.50</price>
    <time>7pm</time>
</gig>

Say if I wanted to view the values of "date" from the gig element which has an attribute of 2 how could I do this using php ?

Basically I want to delete the say id 2 and then create it again or just modify it.

using simpleXML how can I just delete a certain part ?

+1  A: 

To find nodes, use XPath.

$data->xpath('//gig[@id="2"]');

It will return an array with all <gig/> nodes with an attribute id whose value is 2. Usually, it will contain 0 or 1 element. You can modify those directly. For example:

$data = simplexml_load_string(
    '<data>
        <gig id="1">
            <date>December 19th</date>
            <venue>The Zanzibar</venue>
            <area>Liverpool</area>
            <telephone>Ticketline.co.uk</telephone>
            <price>£6</price>
            <time>Time TBA</time>
        </gig>
        <gig id="2">
            <date>Sat. 16th Jan</date>
            <venue>Celtic Connection, Classic Grand</venue>
            <area>Glasgow</area>
            <telephone>0141 353 8000</telephone>
            <price>£17.50</price>
            <time>7pm</time>
        </gig>
    </data>'
);

$nodes = $data->xpath('//gig[@id="2"]');

if (empty($nodes))
{
    // didn't find it
}

$gig = $nodes[0];
$gig->time = '6pm';

die($data->asXML());

Deleting arbitrary nodes is an order of magnitude more complicated, so it's much easier to modify the values rather than deleting/recreating the node.

Josh Davis
I keep getting this error , Fatal error: Call to a member function xpath() on a non-object in /var/www/sm16832/public_html/cms/index.php on line 45
Oliver Bayes-Shelton
In this example, $data is your SimpleXMLElement object. To avoid confusion, *always* name your PHP vars after the node they represent. If the root node is `<data/>` then your PHP var should be `$data`.
Josh Davis