PHPOffice/PHPWord · error · InvalidArgumentException

Invalid text

Error message

Invalid text

What it means

Field::setText() accepts only a string or a TextRun instance as the field's display text. Any other scalar/object (int, array, null-adjacent values, plain Text) throws InvalidArgumentException. The value is only assigned when non-null.

Solutions

  1. Cast the value to a string before calling setText(), e.g. setText((string) $value).
  2. Wrap multiple inline elements in a TextRun and pass that instead.
  3. Pass null (or omit) if you intend no text; null is accepted and skipped.
  4. Add an is_string||TextRun check before the call for dynamic values.

Example fix

// before
$field->setText($count);
// after
$field->setText((string) $count);
Defensive patterns

Strategy: type-guard

Validate before calling

if (null !== $text && !is_string($text) && !$text instanceof \PhpOffice\PhpWord\Element\TextRun) { $text = (string) $text; }

Type guard

function isValidFieldText($text): bool { return $text === null || is_string($text) || $text instanceof \PhpOffice\PhpWord\Element\TextRun; }

Try / catch

try { $field->setText($value); } catch (\InvalidArgumentException $e) { $field->setText((string) $value); }

Prevention

When it happens

Trigger: Calling $field->setText(123), setText(['a']), or setText(new Text('x')) — anything not is_string() and not instanceof TextRun.

Common situations: Passing numeric values from computed data without casting to string, or confusing PhpWord\Element\Text with TextRun.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of PHPOffice/PHPWord@aef95c0415 (2026-09-14). Data as JSON: /api/errors/6591db61b9e237b0. Report an issue: GitHub.

Appendix: source

Thrown at src/PhpWord/Element/Field.php:284

    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Set Field text.
     *
     * @param null|mixed|string|TextRun $text
     *
     * @return null|string|TextRun
     */
    public function setText($text = null)
    {
        if (null !== $text) {
            if (is_string($text) || $text instanceof TextRun) {
                $this->text = $text;
            } else {
                throw new InvalidArgumentException('Invalid text');
            }
        }

        return $this->text;
    }

    /**
     * Get Field text.
     *
     * @return string|TextRun
     */
    public function getText()
    {
        return $this->text;
    }
}

View on GitHub (pinned to aef95c0415)