Pregunta

I am trying to find out how to merge the FIPS part of this XML file into one php variable with SimpleXML.

a sample xml file I'm trying to use is at http://codepad.org/MQeR2VBZ

basically i want a variable with "001033,001077" in it (without the quotes"

I'm new to PHP and this is my first time using stackoverflow so please forgive me if I'm full of fail

¿Fue útil?

Solución

You can solve this easily with XPath.

XPath lets you query for nodes in the document in almost any possible combination. To query for the geocode value that is preceded by a valueName element with the content FIPS6, you can use this query:

/alert/info/area/geocode/value[preceding-sibling::valueName = "FIPS6"]

However, the document has a default namespace for the alert element (as indicated by the xmlns attribute). By default, SimpleXml will not be able to access any namespaced nodes in the document via XPath until we tell it the namespace via registerXPathNamespace and prefix any elements in the query with an arbitrary prefix.

The result of the XPath will be an array containing SimpleXmlElements. When you cast a SimpleXmlElement to string (or use it in a string context), it will return it's nodeValue, which is the values you actually want to combine, so you can simply call implode on the resulting array to combine the values into a string.

Code (demo)

$alert = simplexml_load_file('http://…');
$alert->registerXPathNamespace('a', 'urn:oasis:names:tc:emergency:cap:1.1');
$fipsValues = implode(',', $alert->xpath(
    '/a:alert/a:info/a:area/a:geocode/a:value[
        preceding-sibling::a:valueName = "FIPS6"
    ]'
));
print_r($fipsValues); // will contain "001033,001077"

Otros consejos

This should get you started on the right path:

$string = <<<XML
  <?xml version='1.0' encoding='utf-8' standalone='yes'?>
  <?xml-stylesheet href='http://alerts.weather.gov/cap/capatomproduct.xsl' type='text/xsl'?>
    <alert xmlns='urn:oasis:names:tc:emergency:cap:1.1'>
      ....
      [rest of xml here]
      ....
    </alert>
  XML;

  $xml = simplexml_load_string( $string );

  $fips6 = array();
  foreach( $xml->info->area->geocode AS $element ) {
      if( $element->valueName == 'FIPS6' ) {
          $fips6[] = $element->value;
      }
  }

  $value = implode( "," $fips6 );
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top