简体   繁体   English

从XML对象提取数据

[英]Extract data from an XML object

How do i extract the data from that xml object which is a value of a certain array: 我如何从该xml对象中提取数据,该xml对象是某个数组的值:

Array ( [Title] => SimpleXMLElement Object ( 
[0] => The Key of Life; A Metaphysical Investigation ) 
[ASIN] => SimpleXMLElement Object ( [0] => 0982385099 ) ...

say $X is the object, so to print 说$ X是对象,所以要打印

The Key of Life; 生活的关键; A Metaphysical Investigation 形而上学的调查

you do: 你做:

echo $X->Title[0]

Do string typecasting of the object. 对对象进行字符串类型转换。

$variable = (string) $FieldValue[0]; $ variable =(字符串)$ FieldValue [0];

That would work, as SimpleXml has all the children in object type and not string. 这将起作用,因为SimpleXml的所有子代都属于对象类型,而不是字符串。

It's important to understand that you're not working with an array — you're working with a SimpleXMLElement object, which is not the same. 重要的是要了解您不是在使用数组,而是在使用SimpleXMLElement对象,这是不一样的。

  1. Instead of doing $array['key']['subkey'] , you would do $xml->tag->subtag . 而不是执行$array['key']['subkey'] ,而是执行$xml->tag->subtag
  2. SimpleXML nodes are not strings or arrays, although they behave string-like and array-like. 尽管SimpleXML节点的行为类似于字符串和数组,但它们不是字符串或数组。 Make sure you always typecast the value to an explicit string. 确保始终将值强制转换为显式字符串。
  3. If you're accessing the first node, you don't need to use [0] . 如果要访问第一个节点,则无需使用[0] It's assumed. 是假设的。
  4. You can convert SimpleXMLElement objects into true associative arrays in PHP 5.2 or newer with: 您可以使用以下方法在PHP 5.2或更高版本中将SimpleXMLElement对象转换为真正的关联数组:

    $array = json_decode(json_encode($xml), true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM