0

I am new to processing and reading XML strings in PHP

I have XML like this

<sports-metadata>
  <sports-content-codes>
    <sports-content-code code-type="sport" code-key="15027000" code-name="Golf"/>
    <sports-content-code code-type="league" code-key="l.pga.com" code-name="Professional Golf Association"/>
    <sports-content-code code-type="season-type" code-key="regular"/>
    <sports-content-code code-type="season" code-key="2015"/>
    <sports-content-code code-type="priority" code-key="normal"/>
  </sports-content-codes>
</sports-metadata>

I have read in the XML via a $xml=simplexml_load_file()

I can get to this XML section via $xml->{'sports-content-codes'}->{'sports-content-code'}

In sports-content-code

I want to access/retrieve the code-key value where code-type="season"

How can I do this in PHP?

Thank you all.

-- Ed

hakre
  • 193,403
  • 52
  • 435
  • 836
  • You do that in PHP by selecting the element with the attribute value condition you have and then get the attribute. See [the duplicate question](http://stackoverflow.com/q/992450/367456) and for reading attributes see another duplicate: [How to get the value of an attribute from XML file in PHP?](http://stackoverflow.com/q/1256796/367456) – hakre Oct 10 '14 at 13:02

2 Answers2

2

Usually you use ->attributes() method to get those attributes:

foreach($xml->{'sports-content-codes'}->{'sports-content-code'} as $content_code) {
    $attr = $content_code->attributes();
    $code_type = (string) $attr->{'code-type'};
    echo $code_type;
}

Sample Output

Kevin
  • 41,694
  • 12
  • 53
  • 70
1

Use Xpath ...

... with SimpleXml:

$element = simplexml_load_string($xml);
$array = $element->xpath(
  '//sports-content-code[@code-type="season"]'
);
var_dump(
  (string)$array[0]['code-key']
);

... or DOM:

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
var_dump(
  $xpath->evaluate(
    'string(//sports-content-code[@code-type="season"]/@code-key)'
  )
);

Output (both):

string(4) "2015"

Xpath is a expression language for DOM (think SQL for DBMS). SimpleXMLElement::xpath() supports some of it (only expressions that return element or attribute nodes). The result will always be an array of SimpleXMLElement objects. DOMXpath::evaluate() supports full Xpath 1.0. The result is a DOMNodelist or a scalar value, depending on the expression.

The expression:

Select the "sports-content-code" element nodes

//sports-content-code

with a "code-type" attribute node is season

//sports-content-code[@code-type="season"]

get the "code-key" attribute nodes

//sports-content-code[@code-type="season"]/@code-key

cast the node list to a string returning the text content of the first node

string(//sports-content-code[@code-type="season"]/@code-key)

ThW
  • 19,120
  • 3
  • 22
  • 44