views:

94

answers:

2

Hello i have the follow problem.

I have e XML file and i know the value of "uniquename=value2". I want extract the value of URL.

<set uniquename="value1">
  <items>
    <item>
      <units>
         ...
      </units>
    </item>
    <item>
      <units>
        ...
        <url>http://www.something&lt;/url&gt;
        ...
      </units>
    </item>
  </items>
 </set>
 <set uniquename="value2">
  <items>
    <item>
      <units>
         ...
      </units>
    </item>
    <item>
      <units>
        ...
        <url>http://www.something2&lt;/url&gt;
        ...
      </units>
    </item>
  </items>
 </set>

Someone has suggestions?

Thanks to all.

+4  A: 

You can do it simply with simplexml and xpath:

$x = simplexml_load_string($xml);
$nodes = $x->xpath('set[@uniquename="value2"]/items/item/units/url');

$url = (string)$nodes[0];
Greg
+1, simple and clean answer. I had started to respond with an answer about simplexml, and then realized I hadn't done a lot of work with it and I wasn't sure what the object structure would be like, or how to access it. That's what I love about SO... you always learn something.
zombat
Oops, nitpick point. The poster's xml is in a file, so you'd probably want to use `simplexml_load_file()` instead.
zombat
A: 

Thank's Greg but i have a problem with your code or other:

Warning: simplexml_load_string()....
....
Fatal error: Call to a member function xpath() on a non-object in...

I have read the documentation but don't understand the problem in the format xml file. I have write this code:

<?php
 $value = $_POST["idtag"];
 if (file_exists('external.xml')) {
    $xml = simplexml_load_file('external.xml');
    $x = simplexml_load_string($xml);
    $nodes = $x->xpath('set[@uniquename="$value"]/items/item/units/videoUnit/url');
    $url = (string)$nodes[0];
 }
 else "Failed to open file";
?>

I have forgotten or something wrong?

Thanks for any help

Wyvern
I missed you had a file not a string - just remove "$x = simplexml_load_string($xml);" and change $x-> to $xml->
Greg